package com.alibaba.citrus.ots.application.report.ability.facade.job;

import com.alibaba.citrus.ots.application.report.ability.repository.AllocateOrderDetailRepository;
import com.alibaba.citrus.ots.application.report.ability.repository.BaseDataQueryRepository;
import com.alibaba.citrus.ots.application.report.ability.repository.OrderProgressMonitorReportQueryRepository;
import com.alibaba.citrus.ots.application.report.ability.repository.OrderProgressMonitorReportWriteReporitory;
import com.alibaba.citrus.ots.application.report.ability.repository.PlanContractQuantityRepository;
import com.alibaba.citrus.ots.application.report.ability.repository.SalesPlanDetailRepository;
import com.alibaba.citrus.ots.application.report.ability.utils.DomUtil;
import com.alibaba.citrus.ots.application.report.ability.utils.ObjectEqualsUtil;
import com.alibaba.citrus.ots.application.report.ability.utils.PageRecordUtil;
import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.citrus.ots.sales.plan.model.enums.ContractDataSourceEnum;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.OrgMonthPlanQuantitySDO;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.model.dto.PlatformSDO;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.sales_plan.contract.model.Contract;
import com.epoch.app.bcorder.sales_plan.monthlyplanofccommerce.model.MonthlyPlanOfCcommerce;
import com.epoch.app.bcorder.sales_plan.salesplanscitem.model.SalesPlanScItem;
import com.epoch.app.otsapplicationreportsdk.model.dto.BatchQueryContractQuantityRequest;
import com.epoch.app.otsapplicationreportsdk.model.dto.CommPageQueryRequest;
import com.epoch.app.otsapplicationreportsdk.model.dto.OrderProgressMonitorReportSDO;
import com.epoch.app.otsapplicationreportsdk.model.dto.QueryOrderMonitorReportRequest;
import com.epoch.app.otsapplicationreportsdk.orderprogressmonitorreportwrite.dto.BatchGenerateOrderProgressReportJobRequest;
import com.epoch.app.otsapplicationreportsdk.orderprogressmonitorreportwrite.dto.GenerateOrderProgressReportJobRequest;
import com.epoch.app.otsapplicationreportsdk.orderprogressmonitorreportwrite.service.OrderProgressMonitorReportWriteService;
import com.epoch.app.crplatformenhance.domain.customersalescope.dto.LoadCustomerSaleScopeList2Request;
import com.epoch.app.crplatformenhance.domain.customersalescope.model.CustomerSaleScope;
import com.epoch.app.crplatformenhance.domain.customersalescope.service.CustomerSaleScopeService;
import com.epoch.app.crplatformenhance.model.dto.GetDownOrganizationListRequest;
import com.epoch.app.crplatformenhance.sdo.CustomerAddressSDO;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.crunifiedinventory.model.dto.MonthOrderQuantitySDO;
import com.epoch.app.crunifiedinventory.model.dto.WmsSDO;
import com.google.common.collect.Lists;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhoubc
 * @description: TODO
 * @date 2021/12/29 23:37
 */
@Primary
@Component
public class OrderProgressMonitorReportSyncJob implements OrderProgressMonitorReportWriteService {

    Log log = Log.getLogger(OrderProgressMonitorReportSyncJob.class);

    private final String ORDER_QUANTITY = "orderQuantity";
    private final String ACCUMULATIVE_ORDER_QUANTITY = "accumulativeOrderQuantity";
    private final String MONTH_FIRST_TASK_MONEY = "monthFirstTaskMoney";
    private final String MONTH_MIDDLE_TASK_MONEY = "monthMiddleTaskMoney";
    private final String MONTH_LAST_TASK_MONEY = "monthLastTaskMoney";

    @Resource
    BaseDataQueryRepository baseDataQueryRepository;
    @Resource
    PlanContractQuantityRepository planContractQuantityRepository;
    @Resource
    AllocateOrderDetailRepository allocateOrderDetailRepository;
    @Resource
    SalesPlanDetailRepository salesPlanDetailRepository;
    @Resource
    OrderProgressMonitorReportWriteReporitory orderProgressMonitorReportWriteReporitory;
    @Resource
    OrderProgressMonitorReportQueryRepository orderProgressMonitorReportQueryRepository;
    @Resource
    CrPlatformEnhanceService otsPlatformEnhanceService;
    @Resource
    CustomerSaleScopeService customerSaleScopeService;
    @Resource(name="monthSalesReportTaskExecutor")
    ThreadPoolTaskExecutor monthSalesReportTaskExecutor;

    private final int PageSize_500 = 500;

    private final String nykTjSalesOrgCode = "6140";
    private final String nykBjSalesOrgCode = "2827";
    private final String commerceSalesOrgCode = "1171";
    private final String enterpriseGroupOrgCode = "6000";

    @Override
    @FacadeInvoker
    public Result<Void> batchGenerateOrderProgressReportJob(BatchGenerateOrderProgressReportJobRequest batchGenerateOrderProgressReportJobRequest) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date beginStatisticalDate = null;
        Date endStatisticalDate = null;
        try {
            beginStatisticalDate = format.parse(batchGenerateOrderProgressReportJobRequest.getBeginStatisticalDate());
            endStatisticalDate = format.parse(batchGenerateOrderProgressReportJobRequest.getEndStatisticalDate());
        } catch (ParseException e) {
            return Result.fail("","入参日期格式错误");
        }
        if(beginStatisticalDate.getTime()>endStatisticalDate.getTime()){
            return Result.fail("","开始统计日期大于结束统计日期");
        }
        int betweenDays = DomUtil.getBetweenDays(batchGenerateOrderProgressReportJobRequest.getBeginStatisticalDate(),batchGenerateOrderProgressReportJobRequest.getEndStatisticalDate());
        if(betweenDays >31 ){
            return Result.fail("","开始结束统计日期间隔过大");
        }

        String statisticalDate = batchGenerateOrderProgressReportJobRequest.getBeginStatisticalDate();
        for(int i = 1; i<=31; i++){
            if(i!=1){
                statisticalDate = DomUtil.getRollbackDate(DateUtils.parse(statisticalDate),1);
            }
            if(statisticalDate.equals(DomUtil.getRollbackDate(endStatisticalDate,1))){
                break;
            }
            log.info("batchGenerateOrderProgressReportJob_start,{}",statisticalDate);
            GenerateOrderProgressReportJobRequest request = new GenerateOrderProgressReportJobRequest();
            request.setStatisticalDate(statisticalDate);
            try {
                Result<Void> result = generateOrderProgressReportJob(request);
            } catch (Exception e) {
                log.error("batchGenerateOrderProgressReportJob_statistical_occur_error,statisticalDate={},{}",statisticalDate,e.getMessage());
            }
            log.info("batchGenerateOrderProgressReportJob_end,{}",statisticalDate);
            try {
                Thread.sleep(10000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.success(null);
    }

    @Override
    @FacadeInvoker
    public Result<Void> generateOrderProgressReportJob(GenerateOrderProgressReportJobRequest generateOrderProgressReportJobRequest) {
        //初始化参数
        JobInitParam jobInitParam = init(generateOrderProgressReportJobRequest);
        boolean success = executeGenerateOrderProgressOrganizationReport(jobInitParam);
        if(success){
            CompletableFuture<Void> task1 = executeGenerateOrderProgressBusinessUnitReport(jobInitParam);
            CompletableFuture<Void> task2 = executeGenerateOrderProgressNykReport(jobInitParam);
            CompletableFuture<Void> task3 = executeGenerateOrderProgressCommerceReport(jobInitParam);
            CompletableFuture.allOf(task1, task2, task3).join();
        }
        return Result.success(null);
    }

    @FacadeInvoker
    private JobInitParam init(GenerateOrderProgressReportJobRequest jobRequest){
        //初始化日期参数
        Date todayDate = StringUtil.isNotEmpty(jobRequest.getStatisticalDate())?DateUtils.parse(jobRequest.getStatisticalDate()):new Date();
        String today = DateUtils.formatDate(todayDate,"yyyy-MM-dd");
        String yesterday = DomUtil.isFirstDayOfMonth(todayDate)?today:DomUtil.getYesterdayByDate(todayDate);//如果是月1号昨天日期取今天
        String oneMonthAgo = DomUtil.getRollbackDate(todayDate,-31);
        Date oneMonthAgoDate = DateUtils.parse(oneMonthAgo);
        String twoMonthAgo = DomUtil.getRollbackDate(todayDate,-60);
        Date twoMonthAgoDate = DateUtils.parse(twoMonthAgo);
        String thisMonth = DomUtil.getMonth(todayDate);
        String thisMonthTimestamp = DomUtil.getMonthTimestamp(todayDate);

        //当天是否第一次统计报表
        QueryOrderMonitorReportRequest queryReportRequest = new QueryOrderMonitorReportRequest();
        queryReportRequest.setStatisticalDate(today);
        queryReportRequest.setBizType(103);
        PageResult<List<OrderProgressMonitorReportSDO>> pageResult1 = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryReportRequest);
        Boolean isFirstSyncBusinessUnitReport = pageResult1.getTotal() > 0?false:true;
        queryReportRequest.setBizType(104);
        PageResult<List<OrderProgressMonitorReportSDO>> pageResult2 = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryReportRequest);
        Boolean isFirstSyncSalesOrgReport = pageResult2.getTotal() > 0?false:true;
        queryReportRequest.setBizType(105);
        PageResult<List<OrderProgressMonitorReportSDO>> pageResult3 = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryReportRequest);
        Boolean isFirstSyncSalesChannelReport = pageResult3.getTotal() > 0?false:true;
//        queryReportRequest.setBizType(106);
//        PageResult<List<OrderProgressMonitorReportSDO>> pageResult4 = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryReportRequest);
//        Boolean isAddSalesDepartemntReport = pageResult4.getTotal() > 0?false:true;

        JobInitParam jobInitParam = new JobInitParam();
        jobInitParam.setTodayDate(todayDate);
        jobInitParam.setOneMonthAgo(oneMonthAgo);
        jobInitParam.setOneMonthAgoDate(oneMonthAgoDate);
        jobInitParam.setTwoMonthAgo(twoMonthAgo);
        jobInitParam.setTwoMonthAgoDate(twoMonthAgoDate);
        jobInitParam.setYesterday(yesterday);
        jobInitParam.setToday(today);
        jobInitParam.setThisMonthTimestamp(thisMonthTimestamp);
        jobInitParam.setThisMonth(thisMonth);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(todayDate);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int month = calendar.get(Calendar.MONTH) + 1;
        int year = calendar.get(Calendar.YEAR);
        int daysOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        String whenOfMonth = "";
        if(day <= 10){
            whenOfMonth = "early";
        }else if(day > 10 && day <= 20){
            whenOfMonth = "middle";
        }else if(day > 20){
            whenOfMonth = "late";
        }
        jobInitParam.setDays(day);
        jobInitParam.setMonth(String.valueOf(month));
        jobInitParam.setYear(String.valueOf(year));
        jobInitParam.setWhenOfMonth(whenOfMonth);
        jobInitParam.setDaysOfMonth(daysOfMonth);
        jobInitParam.setIsFirstSyncBusinessUnitReport(isFirstSyncBusinessUnitReport);
        jobInitParam.setIsFirstSyncSalesOrgReport(isFirstSyncSalesOrgReport);
        jobInitParam.setIsFirstSyncChannelOrgReport(isFirstSyncSalesChannelReport);

        //电商、牛要客组织信息填充
        List<String> orgCodes = Lists.newArrayList(nykTjSalesOrgCode,nykBjSalesOrgCode,commerceSalesOrgCode,enterpriseGroupOrgCode);
        Map<String, OrganizationSDO> orgCodeMap = baseDataQueryRepository.batchQueryOrganizationByOutCodes(orgCodes);
        jobInitParam.setNykTjSalesOrg(orgCodeMap.get(nykTjSalesOrgCode));
        jobInitParam.setNykBjSalesOrg(orgCodeMap.get(nykBjSalesOrgCode));
        jobInitParam.setCommerceSalesOrg(orgCodeMap.get(commerceSalesOrgCode));
        jobInitParam.setEnterpriseGroupOrg(orgCodeMap.get(enterpriseGroupOrgCode));
        List<String> parentOrgIds = orgCodeMap.entrySet().stream().map(x -> x.getValue().getParentId()).collect(Collectors.toList());
        Map<String, OrganizationSDO> parentOrgMap = baseDataQueryRepository.batchQueryOrganization(parentOrgIds);
        jobInitParam.setNykTjCompanyOrg(jobInitParam.getNykTjSalesOrg() == null?new OrganizationSDO():parentOrgMap.get(jobInitParam.getNykTjSalesOrg().getParentId()));
        jobInitParam.setNykBjCompanyOrg(jobInitParam.getNykBjSalesOrg() == null?new OrganizationSDO():parentOrgMap.get(jobInitParam.getNykBjSalesOrg().getParentId()));
        jobInitParam.setCommerceCompanyOrg(jobInitParam.getCommerceSalesOrg() == null?new OrganizationSDO():parentOrgMap.get(jobInitParam.getCommerceSalesOrg().getParentId()));

        //查询所有销售组织31天内的每日订单金额和每日进度累计订单金额 （组织，日期，订单SDO）
        Map<String,Map<String,MonthOrderQuantitySDO>> allocateOrderStatMap = querySalesOrgOrderQuantity(jobInitParam);
        jobInitParam.setAllocateOrderStatisticalMap(allocateOrderStatMap);
        //查询原报表数据 (组织，SDO)
        Map<String,OrderProgressMonitorReportSDO> reportMap = queryOldReport(jobInitParam.getToday());
        jobInitParam.setReportMap(reportMap);
        //查询月初报表数据 (组织，SDO)
        Map<String,OrderProgressMonitorReportSDO> beginOfMonthReportMap = queryOldReport(jobInitParam.getThisMonth()+"-01");
        jobInitParam.setBeginOfMonthReportMap(beginOfMonthReportMap);

        return jobInitParam;
    }

    @FacadeInvoker
    public Boolean executeGenerateOrderProgressOrganizationReport(JobInitParam jobInitParam){
        Map<String,Map<String,MonthOrderQuantitySDO>> allocateOrderStatMap = jobInitParam.getAllocateOrderStatisticalMap();
        Map<String,OrderProgressMonitorReportSDO> oldReport = jobInitParam.getReportMap();
        //更新当天数据
        Integer orgType = 104;
        PageRecordUtil pageUtil = new PageRecordUtil();
        pageUtil.simpleResetPageParam();
        CommPageQueryRequest queryRequest = CommPageQueryRequest.builder()
                .limit(pageUtil.getPageSize())
                .build();
        queryRequest.setPlanMonth(jobInitParam.getThisMonthTimestamp());
        queryRequest.setBizType(orgType);
        for (int i = 1; i <= pageUtil.getPage(); i++) {
            queryRequest.setStart(pageUtil.getStart());
            //分页查询月度计划任务数据 -》销售组织 取分解任务量
            PageResult<List<OrgMonthPlanQuantitySDO>> planTaskPageResult = salesPlanDetailRepository.pageStatisticalTaskCountByOrganiztion(queryRequest);
            if(i == 1){
                if(planTaskPageResult.getTotal() <= 0){
                    log.warn("<销售组织订单监控>{}month plan data is null",jobInitParam.getThisMonth());
                    break;
                }
                pageUtil.setTotalPages(planTaskPageResult.getTotal());
            }
            List<String> orgIds = planTaskPageResult.getContent().stream().map( x -> {
                return x.getOrganizationId();
            }).collect(Collectors.toList());

            //根据组织批量查询本月的合同量金额
            Map<String, BigDecimal> contractQuantityMap = queryContractQuantity(jobInitParam,orgIds,String.valueOf(orgType));
            //批量查询组织信息
            Map<String, OrganizationSDO> orgInfoMap = baseDataQueryRepository.batchQueryOrganization(orgIds);

            planTaskPageResult.getContent().forEach( x ->{
                //订单量
                Map<String,BigDecimal> amountMap = getOrderQuantity(allocateOrderStatMap,x.getOrganizationId(),jobInitParam.getToday());
                //计算完成率
                OrderProgressMonitorReportSDO bean = convertAndCountOrderComplete(jobInitParam,x,orgInfoMap,contractQuantityMap,
                        amountMap.get(ORDER_QUANTITY),amountMap.get(ACCUMULATIVE_ORDER_QUANTITY),orgType);
                //判断是否第一次更新数据
                if(jobInitParam.getIsFirstSyncSalesOrgReport()){
                    String id = orderProgressMonitorReportWriteReporitory.add(bean);
                    log.info("<销售组织订单监控>新增数据，id=={}，{}",id, JSON.toJSONString(bean));
                }else{
                    Map<String,Object> res = getAction(bean,oldReport.get(bean.getOrganizationId()));
                    log.info("<销售组织订单监控>计算数据完成后判断行动点结果,action={},old={},new={}",res.get("action"),JSON.toJSON(res.get("oldData")),bean);
                    if("add".equals(res.get("action"))){
                        String id = orderProgressMonitorReportWriteReporitory.add(bean);
                        log.info("<销售组织订单监控>新增数据2，id=={}，{}",id, JSON.toJSONString(bean));
                    }else if("update".equals(res.get("action"))){
                        int count = orderProgressMonitorReportWriteReporitory.update(bean);
                        log.info("<销售组织订单监控>更新数据，更新了{}条数据，{}",count, JSON.toJSONString(bean));
                    }
                }
            });
            pageUtil.turnPage();
        }

        //电商订单统计
        List<OrderProgressMonitorReportSDO> commerceReportList = executeGenerateOrderProgressCommerceSalesOrgReport(jobInitParam);

        //更新60天内的报表数据订单量
        QueryOrderMonitorReportRequest queryRequest2 = new QueryOrderMonitorReportRequest();
        queryRequest2.setBizType(orgType);
        queryRequest2.setLimit(PageSize_500*2);
        String statisticalDate = jobInitParam.getToday();
        for(int j = 1; j<60; j++){
            statisticalDate = DomUtil.getYesterdayByDate(DateUtils.parse(statisticalDate));
            queryRequest2.setStatisticalDate(statisticalDate);
            PageResult<List<OrderProgressMonitorReportSDO>> result = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryRequest2);
            if(result.getTotal()==0){
                continue;
            }

            for(OrderProgressMonitorReportSDO bean:result.getContent()){
                //获取调拨订单量
                Map<String,BigDecimal> orderQuantityMap = new HashMap<>();
                if(commerceSalesOrgCode.equals(bean.getOrganizationCode())){
                    List<String> queryOrgIds = Lists.newArrayList(jobInitParam.getCommerceCompanyOrg().getId(),jobInitParam.getCommerceSalesOrg().getId());
                    orderQuantityMap = getOrderQuantityByOrgIds(allocateOrderStatMap,queryOrgIds,statisticalDate);
                }else{
                    String salesOrgId = bean.getOrganizationId();
                    orderQuantityMap = getOrderQuantity(allocateOrderStatMap,salesOrgId,statisticalDate);
                }
                //日订单金额
                BigDecimal orderQuantity = orderQuantityMap.get(ORDER_QUANTITY)!=null?orderQuantityMap.get(ORDER_QUANTITY):new BigDecimal(0);
                //累计订单金额
                BigDecimal accumulativeOrderQuantity = orderQuantityMap.get(ACCUMULATIVE_ORDER_QUANTITY)!=null?orderQuantityMap.get(ACCUMULATIVE_ORDER_QUANTITY):new BigDecimal(0);

                //判断新统计的订单量数据与旧数据的订单量和累计订单量值一样，跳过
                if(bean.getOrderQuantity().compareTo(orderQuantity) == 0 && bean.getAccumulativeOrderQuantity().compareTo(accumulativeOrderQuantity) == 0){
                    continue;
                }
                //重新计算报表数据
                recountOrderComplete(bean,orderQuantity,accumulativeOrderQuantity);
                int count = orderProgressMonitorReportWriteReporitory.update(bean);
                log.info("<销售组织订单监控>{}executeGenerateOrderProgressOrganizationReport_update_history，update_size={}，data={}",statisticalDate, count, JSON.toJSONString(bean));
            };
        }

        //计划有改动更新月度统计报表数据
        executeCommercePlanChangeUpdateReport(jobInitParam,commerceReportList);
        return true;
    }

    @FacadeInvoker
    public CompletableFuture<Void> executeGenerateOrderProgressBusinessUnitReport(JobInitParam jobInitParam){
        return CompletableFuture.runAsync(() -> {
            Map<String,OrderProgressMonitorReportSDO> oldReport = jobInitParam.getReportMap();
            //通过销售组织统计的数据汇总到分子公司维度
            Integer orgType = 103;
            CommPageQueryRequest queryRequest = CommPageQueryRequest.builder()
                    .limit(PageSize_500*2)
                    .build();
            queryRequest.setPlanMonth(jobInitParam.getThisMonthTimestamp());
            //分子公司月度累计调整量
            //List<OrgMonthPlanQuantitySDO> adjustQuantityList = salesPlanDetailRepository.statisticalAdjustCountByOrganiztion(queryRequest);
            //Map<String,OrgMonthPlanQuantitySDO> adjustQuantityMap = Nullable.stream(adjustQuantityList).collect(Collectors.toMap(e -> e.getOrganizationId()+"-"+e.getScItemId(), Function.identity(),(v1, v2)->v1));
            List<OrgMonthPlanQuantitySDO> adjustQuantityList = salesPlanDetailRepository.queryAdjustCountByOrganiztion(queryRequest);
            Map<String,List<OrgMonthPlanQuantitySDO>> adjustQuantityMap = Nullable.stream(adjustQuantityList).collect(Collectors.groupingBy(OrgMonthPlanQuantitySDO::getOrganizationId));
            //分子公司月度实际任务量
            List<OrgMonthPlanQuantitySDO> planItemGetTaskList = getPlanScItemListGetTask(jobInitParam);
            Map<String,OrgMonthPlanQuantitySDO> taskQuantityMap = Nullable.stream(planItemGetTaskList).collect(Collectors.toMap(e -> e.getOrganizationId()+"-"+e.getScItemId(), Function.identity(),(v1, v2)->v1));
            //分子公司x货品价格
            List<SalesPlanScItem> scItemPriceList = getPlanScItemPriceList(null,null);
            Map<String,SalesPlanScItem> scItemPriceMap = Nullable.stream(scItemPriceList).collect(Collectors.toMap(e -> e.getOrgBusinessUnitCode()+"-"+e.getScItemId(), Function.identity(),(v1, v2)->v1));
            //分页查询月度计划任务数据 -》分子公司 取CRM回复量   分子公司x货品
            List<OrgMonthPlanQuantitySDO> planItemList = getPlanScItemList(jobInitParam,orgType);
            planItemList.forEach(x ->{
                computePlanTaskMoney(x,adjustQuantityMap,taskQuantityMap,scItemPriceMap);
            });
            List<OrgMonthPlanQuantitySDO> orgPlanList = new ArrayList<>();
            Map<String, List<OrgMonthPlanQuantitySDO>> groupBy = planItemList.stream().collect(Collectors.groupingBy(OrgMonthPlanQuantitySDO::getOrganizationId));
            for (Map.Entry<String, List<OrgMonthPlanQuantitySDO>> m : groupBy.entrySet()) {
                OrgMonthPlanQuantitySDO tmp = new OrgMonthPlanQuantitySDO();
                tmp.setOrganizationId(m.getKey());
                List<OrgMonthPlanQuantitySDO> list = m.getValue();
                tmp.setMonthFirstTaskMoney(list.stream().map(OrgMonthPlanQuantitySDO::getMonthFirstTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
                tmp.setMonthMiddleTaskMoney(list.stream().map(OrgMonthPlanQuantitySDO::getMonthMiddleTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
                tmp.setMonthLastTaskMoney(list.stream().map(OrgMonthPlanQuantitySDO::getMonthLastTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
                orgPlanList.add(tmp);
            }
            List<String> orgIds = groupBy.entrySet().stream().map(x->x.getKey()).collect(Collectors.toList());

            //查询总部订单监控表 通过销售组织维度订单量再次统计得到分子公司维度订单量 (string,组织id,金额)
            Map<String, Map<String, BigDecimal>> companyOrderReport = queryCompanyOrderMonitorReport(jobInitParam.getToday(),orgIds);
            Map<String, BigDecimal> orderQuantityMap = companyOrderReport.get(ORDER_QUANTITY);
            Map<String, BigDecimal> accOrderQuantityMap = companyOrderReport.get(ACCUMULATIVE_ORDER_QUANTITY);
            //根据组织批量查询本月的合同量金额
            Map<String, BigDecimal> contractQuantityMap = queryContractQuantity(jobInitParam,orgIds,String.valueOf(orgType));
            //批量查询组织信息
            Map<String, OrganizationSDO> orgInfoMap = baseDataQueryRepository.batchQueryOrganization(orgIds);

            orgPlanList.forEach( x ->{
                BigDecimal orderQuantity = orderQuantityMap.get(x.getOrganizationId())!=null?orderQuantityMap.get(x.getOrganizationId()):new BigDecimal(0);
                BigDecimal accOrderQuantity = accOrderQuantityMap.get(x.getOrganizationId())!=null?accOrderQuantityMap.get(x.getOrganizationId()):new BigDecimal(0);
                //计算完成率
                OrderProgressMonitorReportSDO bean = convertAndCountOrderComplete(jobInitParam,x,orgInfoMap,contractQuantityMap,orderQuantity,accOrderQuantity,orgType);
                //判读是否第一次更新数据
                if(jobInitParam.getIsFirstSyncBusinessUnitReport()){
                    String id = orderProgressMonitorReportWriteReporitory.add(bean);
                    log.info("<分子公司订单监控>新增数据，id=={}，{}",id, JSON.toJSONString(bean));
                }else{
                    Map<String,Object> res = getAction(bean,oldReport.get(bean.getOrganizationId()));
                    log.info("<分子公司订单监控>计算数据完成后判断行动点结果,action={},old={},new={}",res.get("action"),JSON.toJSON(res.get("oldData")),bean);
                    if("add".equals(res.get("action"))){
                        String id = orderProgressMonitorReportWriteReporitory.add(bean);
                        log.info("<分子公司订单监控>新增数据2，id=={}，{}",id, JSON.toJSONString(bean));
                    }else if("update".equals(res.get("action"))){
                        int count = orderProgressMonitorReportWriteReporitory.update(bean);
                        log.info("<分子公司订单监控>更新数据，更新了{}条数据，{}",count, JSON.toJSONString(bean));
                    }
                }
            });

            //电商订单统计
            List<OrderProgressMonitorReportSDO> commerceReportList = executeGenerateOrderProgressCommerceCompanyReport(jobInitParam);

            //汇总销售组织历史数据到分子公司维度
            QueryOrderMonitorReportRequest queryRequest2 = new QueryOrderMonitorReportRequest();
            queryRequest2.setBizType(orgType);
            queryRequest2.setLimit(PageSize_500*2);
            String statisticalDate = jobInitParam.getToday();
            for(int j = 1; j<60; j++){
                statisticalDate = DomUtil.getYesterdayByDate(DateUtils.parse(statisticalDate));
                queryRequest2.setStatisticalDate(statisticalDate);
                PageResult<List<OrderProgressMonitorReportSDO>> result = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryRequest2);
                if(result.getTotal()==0){
                    continue;
                }
                List<String> ids = result.getContent().stream().map( x -> {
                    return x.getOrganizationId();
                }).collect(Collectors.toList());

                //查询总部订单监控表 通过销售组织维度订单量再次统计得到分子公司维度订单量  (string,组织id,金额)
                Map<String, Map<String, BigDecimal>> companyOrderReport2 = queryCompanyOrderMonitorReport(statisticalDate,ids);
                Map<String, BigDecimal> orderQuantityMap2 = companyOrderReport2.get(ORDER_QUANTITY);
                Map<String, BigDecimal> accOrderQuantityMap2 = companyOrderReport2.get(ACCUMULATIVE_ORDER_QUANTITY);

                for(OrderProgressMonitorReportSDO bean:result.getContent()){
                    //天津蒙牛幸福分子公司除外
                    if(jobInitParam.getNykTjCompanyOrg().getCode().equals(bean.getOrganizationCode())){
                        continue;
                    }
                    //新统计的订单量
                    BigDecimal orderQuantity = orderQuantityMap2.get(bean.getOrganizationId())!=null?orderQuantityMap2.get(bean.getOrganizationId()):new BigDecimal(0);
                    BigDecimal accumulativeOrderQuantity = accOrderQuantityMap2.get(bean.getOrganizationId())!=null?accOrderQuantityMap2.get(bean.getOrganizationId()):new BigDecimal(0);
                    //判断新统计的订单量数据与旧数据的订单量和累计订单量值一样，跳过
                    if(bean.getOrderQuantity().compareTo(orderQuantity) == 0 && bean.getAccumulativeOrderQuantity().compareTo(accumulativeOrderQuantity) == 0){
                        continue;
                    }
                    //重新计算报表数据
                    recountOrderComplete(bean,orderQuantity,accumulativeOrderQuantity);
                    int count = orderProgressMonitorReportWriteReporitory.update(bean);
                    log.info("<分子公司订单监控>{}executeGenerateOrderProgressBusinessUnitReport_update_history，update_size={}，data={}", statisticalDate, count, JSON.toJSONString(bean));
                };
            }

            //计划有改动更新月度统计报表数据
            executeCommercePlanChangeUpdateReport(jobInitParam,commerceReportList);
        }, monthSalesReportTaskExecutor);
    }

    @FacadeInvoker
    public CompletableFuture<Void> executeGenerateOrderProgressNykReport(JobInitParam jobInitParam){
        return CompletableFuture.runAsync(() -> {
            Map<String,Map<String,MonthOrderQuantitySDO>> allocateOrderStatMap = jobInitParam.getAllocateOrderStatisticalMap();
            Map<String,OrderProgressMonitorReportSDO> oldReport = jobInitParam.getReportMap();
            //获取重客组织信息
            List<OrganizationSDO> orgList = Lists.newArrayList(jobInitParam.getNykTjSalesOrg(),jobInitParam.getNykBjSalesOrg());
            Map<String, OrganizationSDO> orgCodeMap = Nullable.stream(orgList).collect(Collectors.toMap(OrganizationSDO::getOutCode, Function.identity(),(v1, v2)->v1));
            if(orgCodeMap.size()<1){
                log.error("<牛要客订单监控>organizaion_is_null_stop_nyk_report");
                return;
            }
            //需统计的销售组织ids
            List<String> orgIds = orgCodeMap.entrySet().stream().map(x -> x.getValue().getId()).collect(Collectors.toList());
            Map<String, OrganizationSDO> orgIdMap = orgCodeMap.entrySet().stream().collect(Collectors.toMap(x -> x.getValue().getId(), x -> x.getValue()));
            //对应的分子公司ids
            List<String> parentOrgIds = orgCodeMap.entrySet().stream().map(x -> x.getValue().getParentId()).collect(Collectors.toList());
            List<OrganizationSDO> parentOrgList = Lists.newArrayList(jobInitParam.getNykTjCompanyOrg(),jobInitParam.getNykBjCompanyOrg());
            Map<String, OrganizationSDO> parentOrgMap = Nullable.stream(parentOrgList).collect(Collectors.toMap(OrganizationSDO::getId, Function.identity(),(v1, v2)->v1));
            //批量查询重客组织的计划货品价格
            List<SalesPlanScItem> scItemPriceList = getPlanScItemPriceList(orgIds,104);
            Map<String, List<SalesPlanScItem>> scItemPriceMap = Nullable.stream(scItemPriceList).collect(Collectors.groupingBy(x-> orgIdMap.get(x.getOrgSalesOrganizationCode()).getParentId()));
            log.info("<牛要客订单监控>nyk_scItemPriceMap_size={},{}",scItemPriceMap.size(),scItemPriceMap);

            //分页查询月度计划任务数据 -》牛要客 取修订确认量  计划x货品维度  默认是天津幸福月度计划
            PageRecordUtil pageUtil = new PageRecordUtil();
            pageUtil.resetPageParam();
            CommPageQueryRequest queryRequest = CommPageQueryRequest.builder()
                    .planMonth(jobInitParam.getThisMonthTimestamp())
                    .limit(pageUtil.getPageSize())
                    .build();
            List<OrgMonthPlanQuantitySDO> planScItemList = new ArrayList<>();
            for (int i = 1; i <= pageUtil.getPage(); i++) {
                queryRequest.setStart(pageUtil.getStart());
                PageResult<List<OrgMonthPlanQuantitySDO>> pageResult = salesPlanDetailRepository.pageStatisticalNykMonthPlanConfirmCount(queryRequest);
                if(i == 1){
                    pageUtil.setTotalPages(pageResult.getTotal());
                }
                planScItemList.addAll(pageResult.getContent());
                pageUtil.turnPage();
            }
            if(CollectionUtils.isEmpty(planScItemList)){
                log.warn("<牛要客订单监控>{}nyk_month_plan_data_is_null",jobInitParam.getThisMonthTimestamp());
                return;
            }
            log.info("<牛要客订单监控>nyk_planScItemList_size={}",planScItemList.size());
            Map<String,List<OrgMonthPlanQuantitySDO>> planScItemMap = planScItemList.stream().collect(Collectors.groupingBy(x-> x.getOrganizationId()));

            //获取调拨单订单量
            Map<String, Map<String,BigDecimal>> orderAmountMap = new HashMap<>();
            orgIds.forEach(id ->{
                Map<String,BigDecimal> orderAmount = getOrderQuantity(allocateOrderStatMap,id,jobInitParam.getToday());
                orderAmountMap.put(orgIdMap.get(id).getParentId(),orderAmount);
            });
            //批量查询重客组织的本月的合同量金额
            Map<String, BigDecimal> contractQuantityMap = queryContractQuantity(jobInitParam,parentOrgIds,"103");
            //计算完成率
            List<OrderProgressMonitorReportSDO> list = convertAndCountOrderComplete2(jobInitParam,parentOrgMap,planScItemMap,scItemPriceMap,orderAmountMap,contractQuantityMap);

            for(OrderProgressMonitorReportSDO bean :list) {
                //判读是否第一次更新数据
                if (jobInitParam.getIsFirstSyncBusinessUnitReport()) {
                    String id = orderProgressMonitorReportWriteReporitory.add(bean);
                    log.info("<牛要客订单监控>新增数据，id=={}，{}", id, JSON.toJSONString(bean));
                } else {
                    Map<String, Object> res = getAction(bean,oldReport.get(bean.getOrganizationId()));
                    log.info("<牛要客订单监控>计算数据完成后判断行动点结果,action={},old={},new={}", res.get("action"), JSON.toJSON(res.get("oldData")), bean);
                    if ("add".equals(res.get("action"))) {
                        String id = orderProgressMonitorReportWriteReporitory.add(bean);
                        log.info("<牛要客订单监控>新增数据2，id=={}，{}", id, JSON.toJSONString(bean));
                    } else if ("update".equals(res.get("action"))) {
                        int count = orderProgressMonitorReportWriteReporitory.update(bean);
                        log.info("<牛要客订单监控>更新数据，更新了{}条数据，{}", count, JSON.toJSONString(bean));
                    }
                }
            }

            //更新31天内的报表数据订单量
            QueryOrderMonitorReportRequest queryRequest2 = new QueryOrderMonitorReportRequest();
            queryRequest2.setBizType(103);
            queryRequest2.setLimit(PageSize_500);
            String statisticalDate = jobInitParam.getToday();
            String nykTjCompanyOrgCode = jobInitParam.getNykTjCompanyOrg().getCode();
            String nykBjCompanyOrgCode = jobInitParam.getNykBjCompanyOrg().getCode();
            for(int j = 1; j<31; j++){
                statisticalDate = DomUtil.getYesterdayByDate(DateUtils.parse(statisticalDate));
                queryRequest2.setStatisticalDate(statisticalDate);
                PageResult<List<OrderProgressMonitorReportSDO>> result = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryRequest2);
                if(result.getTotal()==0){
                    continue;
                }
                List<OrderProgressMonitorReportSDO> tmpList = result.getContent().stream().filter(x -> nykTjCompanyOrgCode.equals(x.getOrganizationCode()) || nykBjCompanyOrgCode.equals(x.getOrganizationCode())).collect(Collectors.toList());

                for(OrderProgressMonitorReportSDO sdo:tmpList){
                    List<OrganizationSDO> salesOrgs = orgCodeMap.values().stream().filter(x -> x.getParentId().equals(sdo.getOrganizationId())).collect(Collectors.toList());
                    if(CollectionUtils.isEmpty(salesOrgs)){
                        continue;
                    }
                    String salesOrg = salesOrgs.get(0).getId();
                    //获取调拨单订单量
                    Map<String,BigDecimal> orderAmount = getOrderQuantity(allocateOrderStatMap,salesOrg,statisticalDate);
                    //日订单金额
                    BigDecimal orderQuantity = orderAmount.get(ORDER_QUANTITY)!=null?orderAmount.get(ORDER_QUANTITY):new BigDecimal(0);
                    //累计订单金额
                    BigDecimal accumulativeOrderQuantity = orderAmount.get(ACCUMULATIVE_ORDER_QUANTITY)!=null?orderAmount.get(ACCUMULATIVE_ORDER_QUANTITY):new BigDecimal(0);
                    //判断新统计的订单量数据与旧数据的订单量和累计订单量值一样，跳过
                    if(sdo.getOrderQuantity().compareTo(orderQuantity) == 0 && sdo.getAccumulativeOrderQuantity().compareTo(accumulativeOrderQuantity) == 0){
                        continue;
                    }
                    //重新计算报表数据
                    recountOrderComplete(sdo, orderQuantity, accumulativeOrderQuantity);
                    int count = orderProgressMonitorReportWriteReporitory.update(sdo);
                    log.info("<牛要客订单监控>{}更新历史统计数据，更新了{}条数据，{}", statisticalDate, count, JSON.toJSONString(sdo));
                }
            }

            //计划有改动更新月度统计报表数据
            executeNykPlanChangeUpdateReport(jobInitParam,list);
        }, monthSalesReportTaskExecutor);
    }

    @FacadeInvoker
    public List<OrderProgressMonitorReportSDO> executeGenerateOrderProgressCommerceSalesOrgReport(JobInitParam jobInitParam){
        //return CompletableFuture.runAsync(() -> {
            Map<String,Map<String,MonthOrderQuantitySDO>> allocateOrderStatMap = jobInitParam.getAllocateOrderStatisticalMap();
            Map<String,OrderProgressMonitorReportSDO> oldReport = jobInitParam.getReportMap();
            Integer orgType = 104;
            //获取电商销售组织信息
            List<OrganizationSDO> orgList = Lists.newArrayList(jobInitParam.getCommerceSalesOrg());
            Map<String, OrganizationSDO> orgCodeMap = Nullable.stream(orgList).collect(Collectors.toMap(OrganizationSDO::getOutCode, Function.identity(),(v1, v2)->v1));
            if(orgCodeMap.size()<1){
                log.error("<电商销售组织订单监控>commerce_organizaion_is_null_stop_commerce_report");
                return new ArrayList<>();
            }
            //需统计的销售组织ids
            List<String> orgIds = orgCodeMap.entrySet().stream().map(x -> x.getValue().getId()).collect(Collectors.toList());
            //Map<String, OrganizationSDO> orgIdMap = orgCodeMap.entrySet().stream().collect(Collectors.toMap(x -> x.getValue().getId(), x -> x.getValue()));
            //对应的分子公司ids
            //List<String> parentOrgIds = orgCodeMap.entrySet().stream().map(x -> x.getValue().getParentId()).collect(Collectors.toList());
            //List<OrganizationSDO> parentOrgList = Lists.newArrayList(jobInitParam.getCommerceCompanyOrg());
            //Map<String, OrganizationSDO> parentOrgMap = Nullable.stream(parentOrgList).collect(Collectors.toMap(OrganizationSDO::getId, Function.identity(),(v1, v2)->v1));
            //批量查询电商组织的计划货品价格
            List<SalesPlanScItem> scItemPriceList = getPlanScItemPriceList(orgIds,orgType);
            Map<String, List<SalesPlanScItem>> scItemPriceMap = Nullable.stream(scItemPriceList).collect(Collectors.groupingBy(x-> x.getOrgSalesOrganizationCode()));
            log.info("<电商销售组织订单监控>commerce_scItemPriceMap_size={},{}",scItemPriceMap.size(),scItemPriceMap);

            //分页查询月度计划任务数据 -》电商 取修订确认量  计划x货品维度
            PageRecordUtil pageUtil = new PageRecordUtil();
            pageUtil.resetPageParam();
            CommPageQueryRequest queryRequest = CommPageQueryRequest.builder()
                    .planMonth(jobInitParam.getThisMonthTimestamp())
                    .limit(pageUtil.getPageSize())
                    .build();
            List<OrgMonthPlanQuantitySDO> planScItemList = new ArrayList<>();
            for (int i = 1; i <= pageUtil.getPage(); i++) {
                queryRequest.setStart(pageUtil.getStart());
                PageResult<List<OrgMonthPlanQuantitySDO>> pageResult = salesPlanDetailRepository.pageStatisticalCommerceMonthPlanConfirmCount(queryRequest);
                if(i == 1){
                    pageUtil.setTotalPages(pageResult.getTotal());
                }
                planScItemList.addAll(pageResult.getContent());
                pageUtil.turnPage();
            }
            if(CollectionUtils.isEmpty(planScItemList)){
                log.warn("<电商销售组织订单监控>{}commerce_month_plan_data_is_null",jobInitParam.getThisMonthTimestamp());
                return new ArrayList<>();
            }
            log.info("<电商销售组织订单监控>commerce_planScItemList_size={}",planScItemList.size());
            Map<String,List<OrgMonthPlanQuantitySDO>> planScItemMap = planScItemList.stream().collect(Collectors.groupingBy(x-> x.getOrganizationId()));

            //用于货品outCode转货品id，取货品价格
            List<String> itemOutCodes = planScItemList.stream().map(OrgMonthPlanQuantitySDO::getScItemId).collect(Collectors.toList());
            Map<String, ScItemSDO> scItemMap = baseDataQueryRepository.batchQueryScItemByOutCodes(itemOutCodes);

            //获取调拨单订单量
            //Map<String,BigDecimal> orderAmount = getOrderQuantity(allocateOrderStatMap,jobInitParam.getCommerceCompanyOrg().getId(),jobInitParam.getToday());
            List<String> queryOrgIds = Lists.newArrayList(jobInitParam.getCommerceCompanyOrg().getId(),jobInitParam.getCommerceSalesOrg().getId());
            Map<String,BigDecimal> orderAmount = getOrderQuantityByOrgIds(allocateOrderStatMap,queryOrgIds,jobInitParam.getToday());

            //批量查询电商销售组织的本月的合同量金额
            Map<String, BigDecimal> contractQuantityMap = queryContractQuantity(jobInitParam,orgIds,String.valueOf(orgType));
            //计算完成率
            List<OrderProgressMonitorReportSDO> list = convertAndCountOrderComplete3(jobInitParam,orgCodeMap,planScItemMap,scItemPriceMap,orderAmount,contractQuantityMap,scItemMap,orgType);

            for(OrderProgressMonitorReportSDO bean :list) {
                //判读是否第一次更新数据
                if (jobInitParam.getIsFirstSyncSalesOrgReport()) {
                    String id = orderProgressMonitorReportWriteReporitory.add(bean);
                    log.info("<电商销售组织订单监控>新增数据，id=={}，{}", id, JSON.toJSONString(bean));
                } else {
                    Map<String, Object> res = getAction(bean,oldReport.get(bean.getOrganizationId()));
                    log.info("<电商销售组织订单监控>计算数据完成后判断行动点结果,action={},old={},new={}", res.get("action"), JSON.toJSON(res.get("oldData")), bean);
                    if ("add".equals(res.get("action"))) {
                        String id = orderProgressMonitorReportWriteReporitory.add(bean);
                        log.info("<电商销售组织订单监控>新增数据2，id=={}，{}", id, JSON.toJSONString(bean));
                    } else if ("update".equals(res.get("action"))) {
                        int count = orderProgressMonitorReportWriteReporitory.update(bean);
                        log.info("<电商销售组织订单监控>更新数据，更新了{}条数据，{}", count, JSON.toJSONString(bean));
                    }
                }
            }
            return list;
        //}, monthSalesReportTaskExecutor);
    }

    @FacadeInvoker
    public List<OrderProgressMonitorReportSDO> executeGenerateOrderProgressCommerceCompanyReport(JobInitParam jobInitParam){
        Map<String,OrderProgressMonitorReportSDO> oldReport = jobInitParam.getReportMap();
        Integer orgType = 103;
        //获取电商销售组织信息
        List<OrganizationSDO> orgList = Lists.newArrayList(jobInitParam.getCommerceSalesOrg());
        Map<String, OrganizationSDO> orgCodeMap = Nullable.stream(orgList).collect(Collectors.toMap(OrganizationSDO::getOutCode, Function.identity(),(v1, v2)->v1));
        if(orgCodeMap.size()<1){
            log.error("<电商分子公司订单监控>commerce_organizaion_is_null_stop_commerce_report");
            return new ArrayList<>();
        }
        //需汇总的销售组织ids
        //List<String> orgIds = orgCodeMap.entrySet().stream().map(x -> x.getValue().getId()).collect(Collectors.toList());
        //分子公司org
        OrganizationSDO companyOrg = jobInitParam.getCommerceCompanyOrg();
        List companyOrgIds = Lists.newArrayList(companyOrg.getId());
        //查询总部订单监控表 通过销售组织维度订单量再次统计得到分子公司维度订单量 (string,组织id,金额)
        Map<String, Map<String, BigDecimal>> companyOrderReport = queryCompanyOrderMonitorReport(jobInitParam.getToday(),companyOrgIds);
        //批量查询电商分子公司的本月的合同量金额
        Map<String, BigDecimal> contractQuantityMap = queryContractQuantity(jobInitParam,companyOrgIds,String.valueOf(orgType));
        //计算完成率
        List<OrderProgressMonitorReportSDO> list = convertAndCountOrderComplete4(jobInitParam,companyOrg,companyOrderReport,contractQuantityMap,orgType);

        for(OrderProgressMonitorReportSDO bean :list) {
            //判读是否第一次更新数据
            if (jobInitParam.getIsFirstSyncBusinessUnitReport()) {
                String id = orderProgressMonitorReportWriteReporitory.add(bean);
                log.info("<电商分子公司订单监控>新增数据，id=={}，{}", id, JSON.toJSONString(bean));
            } else {
                Map<String, Object> res = getAction(bean,oldReport.get(bean.getOrganizationId()));
                log.info("<电商分子公司订单监控>计算数据完成后判断行动点结果,action={},old={},new={}", res.get("action"), JSON.toJSON(res.get("oldData")), bean);
                if ("add".equals(res.get("action"))) {
                    String id = orderProgressMonitorReportWriteReporitory.add(bean);
                    log.info("<电商分子公司订单监控>新增数据2，id=={}，{}", id, JSON.toJSONString(bean));
                } else if ("update".equals(res.get("action"))) {
                    int count = orderProgressMonitorReportWriteReporitory.update(bean);
                    log.info("<电商分子公司订单监控>更新数据，更新了{}条数据，{}", count, JSON.toJSONString(bean));
                }
            }
        }
        return list;
    }

    @FacadeInvoker
    public CompletableFuture<Void> executeGenerateOrderProgressCommerceReport(JobInitParam jobInitParam){
        return CompletableFuture.runAsync(() -> {
            Map<String,OrderProgressMonitorReportSDO> oldReport = jobInitParam.getReportMap();
            //获取电商销售组织信息
            List<OrganizationSDO> salesOrgList = Lists.newArrayList(jobInitParam.getCommerceSalesOrg());
            if(salesOrgList.size()<1){
                log.error("<电商销售渠道订单监控>commerce_organizaion_is_null_stop_commerce_report");
                return;
            }
            //电商月度计划
            List<MonthlyPlanOfCcommerce> planScItemList = getChannelCommerceMonthPlanList(jobInitParam);
            if(CollectionUtils.isEmpty(planScItemList)){
                return;
            }
            //月度计划明细Map
            Map<String,List<MonthlyPlanOfCcommerce>> channelPlanScItemMap = planScItemList.stream().filter(x->StringUtil.isNotEmpty(x.getOrgSaleChannelCode())).collect(Collectors.groupingBy(MonthlyPlanOfCcommerce::getOrgSaleChannelCode));
            Map<String,List<MonthlyPlanOfCcommerce>> platformPlanScItemMap = planScItemList.stream().filter(x->StringUtil.isNotEmpty(x.getCommercePlatform())).collect(Collectors.groupingBy(MonthlyPlanOfCcommerce::getCommercePlatform));

            //用于货品outCode转货品id，取货品价格
            List<String> itemOutCodes = planScItemList.stream().map(MonthlyPlanOfCcommerce::getOuterId).collect(Collectors.toList());
            Map<String, ScItemSDO> scItemMap = baseDataQueryRepository.batchQueryScItemByOutCodes(itemOutCodes);

            //统计调拨单订单量
            List<MonthOrderQuantitySDO> allocateOrderList = getAllocateOrderList(jobInitParam);
            Map<String,List<MonthOrderQuantitySDO>> organizationGroupByMap = allocateOrderList.stream().filter(x->StringUtil.isNotEmpty(x.getOrganizationId())).collect(Collectors.groupingBy(MonthOrderQuantitySDO::getOrganizationId));
            Map<String,Map<String,MonthOrderQuantitySDO>> channelOrgQuantityMap = statisticalAllocateOrderQuantity(jobInitParam,organizationGroupByMap);
            Map<String,List<MonthOrderQuantitySDO>> platformGroupByMap = allocateOrderList.stream().filter(x->StringUtil.isNotEmpty(x.getPlatformId())).collect(Collectors.groupingBy(MonthOrderQuantitySDO::getPlatformId));
            Map<String,Map<String,MonthOrderQuantitySDO>> platformQuantityMap = statisticalAllocateOrderQuantity(jobInitParam,platformGroupByMap);

            Integer channelOrgType = 105;
            Integer platformOrgType = 106;
            //根据销售组织获取电商销售渠道信息
            List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO> channelOrgList = new ArrayList<>();
            GetDownOrganizationListRequest queryDownOrganizationRequest = new GetDownOrganizationListRequest();
            queryDownOrganizationRequest.setType(channelOrgType);
            for (OrganizationSDO org :salesOrgList) {
                queryDownOrganizationRequest.setId(org.getId());
                Result<List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO>> channelOrgResult = otsPlatformEnhanceService.getDownOrganizationList(queryDownOrganizationRequest);
                if (Objects.nonNull(channelOrgResult) || CollectionUtils.isNotEmpty(channelOrgResult.getResult())) {
                    channelOrgList.addAll(channelOrgResult.getResult());
                }
            }
            List<String> channelOrgIds = Nullable.stream(channelOrgList).map(com.epoch.app.crplatformenhance.sdo.OrganizationSDO::getId).collect(Collectors.toList());

            //批量查询电商销售渠道的计划货品价格
            List<SalesPlanScItem> scItemPriceList = getPlanScItemPriceList(channelOrgIds,channelOrgType);
            Map<String, List<SalesPlanScItem>> scItemPriceMap = Nullable.stream(scItemPriceList).collect(Collectors.groupingBy(x-> x.getOrgSalesChannelCode()));
            log.info("<电商销售渠道订单监控>commerce_scItemPriceMap_size={},{}",scItemPriceMap.size(),scItemPriceMap);

            //批量查询电商销售渠道的本月的合同量金额
            Map<String, BigDecimal> contractQuantityMap = queryContractQuantity(jobInitParam,channelOrgIds,String.valueOf(channelOrgType));

            //处理销售渠道订单
            List<OrderProgressMonitorReportSDO> commerceChannelReportList = dealChannelOrder(jobInitParam,channelPlanScItemMap,scItemMap,scItemPriceMap,channelOrgQuantityMap,contractQuantityMap,channelOrgList,channelOrgType,oldReport);
            //处理电商平台订单
            List<OrderProgressMonitorReportSDO> commercePlatformReportList = dealPlatformOrder(jobInitParam,platformPlanScItemMap,scItemMap,scItemPriceMap,platformQuantityMap,contractQuantityMap,platformOrgType,oldReport);

            //更新31天内的报表数据订单量  电商销售渠道
            QueryOrderMonitorReportRequest queryRequest2 = new QueryOrderMonitorReportRequest();
            queryRequest2.setLimit(PageSize_500*2);
            queryRequest2.setBizType(channelOrgType);
            String statisticalDate = jobInitParam.getToday();
            for(int j = 1; j<31; j++){
                statisticalDate = DomUtil.getYesterdayByDate(DateUtils.parse(statisticalDate));
                queryRequest2.setStatisticalDate(statisticalDate);
                PageResult<List<OrderProgressMonitorReportSDO>> result = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryRequest2);
                if(result.getTotal()==0){
                    continue;
                }
                for(OrderProgressMonitorReportSDO bean:result.getContent()){
                    //获取调拨订单量
                    Map<String,BigDecimal> orderQuantityMap = getOrderQuantity(channelOrgQuantityMap,bean.getOrganizationId(),statisticalDate);
                    //日订单金额
                    BigDecimal orderQuantity = orderQuantityMap.get(ORDER_QUANTITY)!=null?orderQuantityMap.get(ORDER_QUANTITY):new BigDecimal(0);
                    //累计订单金额
                    BigDecimal accumulativeOrderQuantity = orderQuantityMap.get(ACCUMULATIVE_ORDER_QUANTITY)!=null?orderQuantityMap.get(ACCUMULATIVE_ORDER_QUANTITY):new BigDecimal(0);
                    //判断新统计的订单量数据与旧数据的订单量和累计订单量值一样，跳过
                    if(bean.getOrderQuantity().compareTo(orderQuantity) == 0 && bean.getAccumulativeOrderQuantity().compareTo(accumulativeOrderQuantity) == 0){
                        continue;
                    }
                    //重新计算报表数据
                    recountOrderComplete(bean,orderQuantity,accumulativeOrderQuantity);
                    int count = orderProgressMonitorReportWriteReporitory.update(bean);
                    log.info("<电商销售渠道订单监控>{}更新历史统计数据，更新了{}条数据，{}",statisticalDate, count, JSON.toJSONString(bean));
                };
            }
            //更新31天内的报表数据订单量  电商平台
            queryRequest2.setBizType(platformOrgType);
            statisticalDate = jobInitParam.getToday();
            for(int j = 1; j<31; j++){
                statisticalDate = DomUtil.getYesterdayByDate(DateUtils.parse(statisticalDate));
                queryRequest2.setStatisticalDate(statisticalDate);
                PageResult<List<OrderProgressMonitorReportSDO>> result = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryRequest2);
                if(result.getTotal()==0){
                    continue;
                }
                for(OrderProgressMonitorReportSDO bean:result.getContent()){
                    //获取调拨订单量
                    Map<String,BigDecimal> orderQuantityMap = getOrderQuantity(platformQuantityMap,bean.getOrganizationId(),statisticalDate);
                    //日订单金额
                    BigDecimal orderQuantity = orderQuantityMap.get(ORDER_QUANTITY)!=null?orderQuantityMap.get(ORDER_QUANTITY):new BigDecimal(0);
                    //累计订单金额
                    BigDecimal accumulativeOrderQuantity = orderQuantityMap.get(ACCUMULATIVE_ORDER_QUANTITY)!=null?orderQuantityMap.get(ACCUMULATIVE_ORDER_QUANTITY):new BigDecimal(0);
                    //判断新统计的订单量数据与旧数据的订单量和累计订单量值一样，跳过
                    if(bean.getOrderQuantity().compareTo(orderQuantity) == 0 && bean.getAccumulativeOrderQuantity().compareTo(accumulativeOrderQuantity) == 0){
                        continue;
                    }
                    //重新计算报表数据
                    recountOrderComplete(bean,orderQuantity,accumulativeOrderQuantity);
                    int count = orderProgressMonitorReportWriteReporitory.update(bean);
                    log.info("<电商平台订单监控>{}更新历史统计数据，更新了{}条数据，{}",statisticalDate, count, JSON.toJSONString(bean));
                };
            }

            //计划有改动更新月度统计报表数据
            executeCommercePlanChangeUpdateReport(jobInitParam,commerceChannelReportList);
            executeCommercePlanChangeUpdateReport(jobInitParam,commercePlatformReportList);

        }, monthSalesReportTaskExecutor);
    }

    @FacadeInvoker
    public void executeCommercePlanChangeUpdateReport(JobInitParam jobInitParam,List<OrderProgressMonitorReportSDO> list){
        //return CompletableFuture.runAsync(() -> {
            Map<String,OrderProgressMonitorReportSDO> beginOfMonthReportMap = jobInitParam.getBeginOfMonthReportMap();
            if(beginOfMonthReportMap.isEmpty()){
                return;
            }

            for(OrderProgressMonitorReportSDO newPlanSDO : list) {
                BigDecimal replyQuantity = newPlanSDO.getReplyQuantity();
                OrderProgressMonitorReportSDO oldReprotBean = beginOfMonthReportMap.get(newPlanSDO.getOrganizationId());
                if(oldReprotBean == null){
                    continue;
                }
                //如果月1号的统计数据和本次统计的全月计划回复量不相等，更新1号到统计日期的所有报表数据
                if(replyQuantity.compareTo(oldReprotBean.getReplyQuantity()) != 0){
                    QueryOrderMonitorReportRequest queryRequest = new QueryOrderMonitorReportRequest();
                    queryRequest.setBizType(newPlanSDO.getBizType());
                    queryRequest.setOrganizationIds(Lists.newArrayList(newPlanSDO.getOrganizationId()));
                    queryRequest.setLimit(PageSize_500);
                    queryRequest.setBeginDate(jobInitParam.getThisMonth()+"-01");
                    queryRequest.setEndDate(jobInitParam.getYesterday());
                    PageResult<List<OrderProgressMonitorReportSDO>> result = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryRequest);
                    if(CollectionUtils.isEmpty(result.getContent())){
                        continue;
                    }
                    for(OrderProgressMonitorReportSDO oldReportBean:result.getContent()){
                        //重新计算报表数据
                        OrderProgressMonitorReportSDO bean = recountCommercePlan(oldReportBean,newPlanSDO);
                        int count = orderProgressMonitorReportWriteReporitory.update(bean);
                        log.info("<电商月度计划监控>monthlyPlanOfCcommerce_update_history，date={}，size={}，{}",bean.getStatisticalDate(), count, JSON.toJSONString(bean));
                    }
                }
            }
        //}, monthSalesReportTaskExecutor);
    }

    @FacadeInvoker
    public void executeNykPlanChangeUpdateReport(JobInitParam jobInitParam,List<OrderProgressMonitorReportSDO> list){
        Map<String,OrderProgressMonitorReportSDO> beginOfMonthReportMap = jobInitParam.getBeginOfMonthReportMap();
        if(beginOfMonthReportMap.isEmpty()){
            return;
        }

        for(OrderProgressMonitorReportSDO newPlanSDO : list) {
            BigDecimal replyQuantity = newPlanSDO.getReplyQuantity();
            OrderProgressMonitorReportSDO oldReprotBean = beginOfMonthReportMap.get(newPlanSDO.getOrganizationId());
            //解决sit环境数据问题
            if(oldReprotBean==null){
                continue;
            }
            //如果月1号的统计数据和本次统计的全月计划回复量不相等，更新1号到统计日期的所有报表数据
            if(replyQuantity.compareTo(oldReprotBean.getReplyQuantity()) != 0){
                QueryOrderMonitorReportRequest queryRequest = new QueryOrderMonitorReportRequest();
                queryRequest.setBizType(newPlanSDO.getBizType());
                queryRequest.setOrganizationIds(Lists.newArrayList(newPlanSDO.getOrganizationId()));
                queryRequest.setLimit(PageSize_500);
                queryRequest.setBeginDate(jobInitParam.getThisMonth()+"-01");
                queryRequest.setEndDate(jobInitParam.getYesterday());
                PageResult<List<OrderProgressMonitorReportSDO>> result = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryRequest);
                if(CollectionUtils.isEmpty(result.getContent())){
                    continue;
                }
                for(OrderProgressMonitorReportSDO oldReportBean:result.getContent()){
                    //重新计算报表数据
                    OrderProgressMonitorReportSDO bean = recountNykPlan(oldReportBean,newPlanSDO);
                    int count = orderProgressMonitorReportWriteReporitory.update(bean);
                    log.info("<牛要客月度计划监控>monthlyPlanOfNyk_update_history，date={}，size={}，{}",bean.getStatisticalDate(), count, JSON.toJSONString(bean));
                }
            }
        }
    }

    private List<OrderProgressMonitorReportSDO> dealChannelOrder(JobInitParam jobInitParam,
                                 Map<String, List<MonthlyPlanOfCcommerce>> channelPlanScItemMap,
                                 Map<String, ScItemSDO> scItemMap,
                                 Map<String, List<SalesPlanScItem>> scItemPriceMap,
                                 Map<String, Map<String,MonthOrderQuantitySDO>> channelOrgQuantityMap,
                                 Map<String, BigDecimal> contractQuantityMap,
                                 List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO> channelOrgList,
                                 Integer orgType,
                                 Map<String,OrderProgressMonitorReportSDO> oldReport){
        //计算完成率
        List<OrderProgressMonitorReportSDO> list = convertAndCountOrderComplete5(jobInitParam,channelOrgList,channelPlanScItemMap,scItemPriceMap,channelOrgQuantityMap,contractQuantityMap,scItemMap,orgType);

        for(OrderProgressMonitorReportSDO bean :list) {
            //判读是否第一次更新数据
            if (jobInitParam.getIsFirstSyncChannelOrgReport()) {
                String id = orderProgressMonitorReportWriteReporitory.add(bean);
                log.info("<电商销售渠道订单监控>新增数据，id=={}，{}", id, JSON.toJSONString(bean));
            } else {
                Map<String, Object> res = getAction(bean,oldReport.get(bean.getOrganizationId()));
                log.info("<电商销售渠道订单监控>计算数据完成后判断行动点结果,action={},old={},new={}", res.get("action"), JSON.toJSON(res.get("oldData")), bean);
                if ("add".equals(res.get("action"))) {
                    String id = orderProgressMonitorReportWriteReporitory.add(bean);
                    log.info("<电商销售渠道订单监控>新增数据2，id=={}，{}", id, JSON.toJSONString(bean));
                } else if ("update".equals(res.get("action"))) {
                    int count = orderProgressMonitorReportWriteReporitory.update(bean);
                    log.info("<电商销售渠道订单监控>更新数据，更新了{}条数据，{}", count, JSON.toJSONString(bean));
                }
            }
        }
        return list;
    }

    private List<OrderProgressMonitorReportSDO> dealPlatformOrder(JobInitParam jobInitParam,
                                  Map<String, List<MonthlyPlanOfCcommerce>> platformPlanScItemMap,
                                  Map<String, ScItemSDO> scItemMap,
                                  Map<String, List<SalesPlanScItem>> scItemPriceMap,
                                  Map<String, Map<String,MonthOrderQuantitySDO>> platformOrgQuantityMap,
                                  Map<String, BigDecimal> contractQuantityMap,
                                  Integer orgType,
                                  Map<String,OrderProgressMonitorReportSDO> oldReport){
        //计算完成率
        List<OrderProgressMonitorReportSDO> list = convertAndCountOrderComplete6(jobInitParam,platformPlanScItemMap,scItemPriceMap,platformOrgQuantityMap,contractQuantityMap,scItemMap,orgType);

        for(OrderProgressMonitorReportSDO bean :list) {
            //判读是否第一次更新数据
            if (jobInitParam.getIsFirstSyncChannelOrgReport()) {
                String id = orderProgressMonitorReportWriteReporitory.add(bean);
                log.info("<电商平台订单监控>新增数据，id=={}，{}", id, JSON.toJSONString(bean));
            } else {
                Map<String, Object> res = getAction(bean,oldReport.get(bean.getOrganizationId()));
                log.info("<电商平台订单监控>计算数据完成后判断行动点结果,action={},old={},new={}", res.get("action"), JSON.toJSON(res.get("oldData")), bean);
                if ("add".equals(res.get("action"))) {
                    String id = orderProgressMonitorReportWriteReporitory.add(bean);
                    log.info("<电商平台订单监控>新增数据2，id=={}，{}", id, JSON.toJSONString(bean));
                } else if ("update".equals(res.get("action"))) {
                    int count = orderProgressMonitorReportWriteReporitory.update(bean);
                    log.info("<电商平台订单监控>更新数据，更新了{}条数据，{}", count, JSON.toJSONString(bean));
                }
            }
        }
        return list;
    }

    //拉取电商月度计划x货品数据
    private List<MonthlyPlanOfCcommerce> getChannelCommerceMonthPlanList(JobInitParam jobInitParam){
        PageRecordUtil pageUtil = new PageRecordUtil();
        pageUtil.resetPageParam();
        CommPageQueryRequest request = new CommPageQueryRequest();
        request.setPlanMonth(jobInitParam.getThisMonthTimestamp());
        request.setLimit(pageUtil.getPageSize());
        List<MonthlyPlanOfCcommerce> list = new ArrayList<>();
        for (int i = 1; i <= pageUtil.getPage(); i++) {
            request.setStart(pageUtil.getStart());
            PageResult<List<MonthlyPlanOfCcommerce>> planItemResult = salesPlanDetailRepository.pageQueryCommerceMonthPlanConfirmCount(request);
            if(i == 1){
                pageUtil.setTotalPages(planItemResult.getTotal());
            }
            list.addAll(planItemResult.getContent());
            pageUtil.turnPage();
        }

        if(CollectionUtils.isNotEmpty(list)){
            Map<String,CustomerSaleScope> resultMap = new HashMap<>();
            Map<String,List<MonthlyPlanOfCcommerce>> groupByMap = list.stream().collect(Collectors.groupingBy(x->x.getOrgSaleOrganizationCode()+"#"+x.getCustomerCode()+"#"+x.getScItemGroupCode()));
            for (Map.Entry<String, List<MonthlyPlanOfCcommerce>> entryOrg: groupByMap.entrySet()){
                String key = entryOrg.getKey();
                String[] array = key.split("#");
                LoadCustomerSaleScopeList2Request scopeRequest = LoadCustomerSaleScopeList2Request.builder()
                        .orgSaleOrganizationCode(array[0])
                        .customerCode(array[1])
                        .itemGroup(array[2])
                        .channelCode("20")
                        .build();
                Result<List<CustomerSaleScope>> response = customerSaleScopeService.loadCustomerSaleScopeList2(scopeRequest);
                if (Objects.nonNull(response) && CollectionUtils.isNotEmpty(response.getResult())) {
                    resultMap.put(key,response.getResult().get(0));
                }
            }
            for (MonthlyPlanOfCcommerce sdo:list) {
                CustomerSaleScope bean = resultMap.get(sdo.getOrgSaleOrganizationCode()+"#"+sdo.getCustomerCode()+"#"+sdo.getScItemGroupCode());
                if(bean != null){
                    sdo.setOrgSaleChannelCode(bean.getOrgSaleChannelCode());
                    sdo.setCommercePlatform(bean.getCommercePlatform());
                }
            }
            List<String> codes = list.stream().map(MonthlyPlanOfCcommerce::getCommercePlatform).collect(Collectors.toList());
            Map<String, PlatformSDO> platformMap = baseDataQueryRepository.batchQueryPlatformsByCodes(codes);
            list = list.stream().map(x ->{
                if(platformMap != null && platformMap.get(x.getCommercePlatform()) != null){
                    x.setOrgSaleDepartmentCode(platformMap.get(x.getCommercePlatform()).getPlatformName());
                }
                return x;
            }).collect(Collectors.toList());
        }
        return list;
    }

    //拉取计划x货品数据
    private List<OrgMonthPlanQuantitySDO> getPlanScItemList(JobInitParam jobInitParam,Integer orgType){
        PageRecordUtil pageUtil = new PageRecordUtil();
        pageUtil.resetPageParam();
        CommPageQueryRequest request = new CommPageQueryRequest();
        request.setPlanMonth(jobInitParam.getThisMonthTimestamp());
        request.setBizType(orgType);
        request.setLimit(pageUtil.getPageSize());
        List<OrgMonthPlanQuantitySDO> list = new ArrayList<>();
        for (int i = 1; i <= pageUtil.getPage(); i++) {
            request.setStart(pageUtil.getStart());
            PageResult<List<OrgMonthPlanQuantitySDO>> planItemResult = salesPlanDetailRepository.pageStatisticalReturnCountByOrganiztion(request);
            if(i == 1){
                pageUtil.setTotalPages(planItemResult.getTotal());
            }
            list.addAll(planItemResult.getContent());
            pageUtil.turnPage();
        }
        return list;
    }

    //拉取计划x货品数据 调整的计划获取实际任务量
    private List<OrgMonthPlanQuantitySDO> getPlanScItemListGetTask(JobInitParam jobInitParam){
        PageRecordUtil pageUtil = new PageRecordUtil();
        pageUtil.resetPageParam();
        CommPageQueryRequest request = new CommPageQueryRequest();
        request.setPlanMonth(jobInitParam.getThisMonthTimestamp());
        request.setLimit(pageUtil.getPageSize());
        List<OrgMonthPlanQuantitySDO> list = new ArrayList<>();
        for (int i = 1; i <= pageUtil.getPage(); i++) {
            request.setStart(pageUtil.getStart());
            PageResult<List<OrgMonthPlanQuantitySDO>> planItemResult = salesPlanDetailRepository.pageStatisticalTaskCountByOrganiztion(request);
            if(i == 1){
                pageUtil.setTotalPages(planItemResult.getTotal());
            }
            list.addAll(planItemResult.getContent());
            pageUtil.turnPage();
        }
        return list;
    }

    //拉取计划x货品价格数据
    private List<SalesPlanScItem> getPlanScItemPriceList(List<String> ids,Integer bizType){
        PageRecordUtil pageUtil = new PageRecordUtil();
        pageUtil.resetPageParam();
        CommPageQueryRequest request = CommPageQueryRequest.builder()
                .organizationIds(ids)
                .bizType(bizType)
                .build();
        request.setLimit(pageUtil.getPageSize());
        List<SalesPlanScItem> list = new ArrayList<>();
        for (int i = 1; i <= pageUtil.getPage(); i++) {
            request.setStart(pageUtil.getStart());
            PageResult<List<SalesPlanScItem>> planPageResult = salesPlanDetailRepository.batchQueryScItemPriceByOrganization(request);
            if(i == 1){
                pageUtil.setTotalPages(planPageResult.getTotal());
            }
            list.addAll(planPageResult.getContent());
            pageUtil.turnPage();
        }
        return list;
    }

    private Map<String,Map<String,MonthOrderQuantitySDO>> statisticalAllocateOrderQuantity(JobInitParam jobInitParam,Map<String,List<MonthOrderQuantitySDO>> map){
        //统计
        Map<String,Map<String,MonthOrderQuantitySDO>> result = new HashMap<>();
        //生成所有组织的每日订单量和累计订单量
        for (Map.Entry<String, List<MonthOrderQuantitySDO>> m : map.entrySet()) {
            String record = jobInitParam.getToday();
            String orgId = m.getKey();
            List<MonthOrderQuantitySDO> orderList = m.getValue();
            //日期分组统计   日期,orderLines
            Map<String, List<MonthOrderQuantitySDO>> statisticalMap = orderList.stream().collect(Collectors.groupingBy(MonthOrderQuantitySDO::getGmtCreateDate));
            List<MonthOrderQuantitySDO> convertList = statisticalMap.entrySet().stream().map(x -> {
                MonthOrderQuantitySDO sdo = new MonthOrderQuantitySDO();
                sdo.setGmtCreateDate(x.getKey());
                BigDecimal amount = x.getValue().stream().map(MonthOrderQuantitySDO::getOrderAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
                sdo.setOrderAmount(amount);
                return sdo;
            }).collect(Collectors.toList());
            Map<String,MonthOrderQuantitySDO> orderMap = convertList.stream().collect(Collectors.toMap(MonthOrderQuantitySDO::getGmtCreateDate, Function.identity(),(v1, v2)->v1));
            //生成31天内的每天订单量SDO
            List<MonthOrderQuantitySDO> newList = new ArrayList<>();
            for(int i =0;i<31;i++){
                MonthOrderQuantitySDO quantitySDO = new MonthOrderQuantitySDO();
                quantitySDO.setOrganizationId(orgId);
                quantitySDO.setGmtCreateDate(record);
                quantitySDO.setOrderAmount(orderMap.get(record)!=null?orderMap.get(record).getOrderAmount():new BigDecimal(0));
                Date statEndDate = DateUtils.parse(record);
                Date statBeginDate = DomUtil.getStartTimeOfMonth(statEndDate);
                List<MonthOrderQuantitySDO> accList = convertList.stream().filter(s -> statBeginDate.compareTo(DateUtils.parse(s.getGmtCreateDate()))<=0 && statEndDate.compareTo(DateUtils.parse(s.getGmtCreateDate()))>=0 ).collect(Collectors.toList());
                BigDecimal accOrderAmount = CollectionUtils.isNotEmpty(accList)?accList.stream().map(MonthOrderQuantitySDO::getOrderAmount).reduce(BigDecimal.ZERO,BigDecimal::add):new BigDecimal(0);
                quantitySDO.setAccumulativeOrderAmount(accOrderAmount);
                newList.add(quantitySDO);
                record = DomUtil.getRollbackDate(DateUtils.parse(record),-1);
            }
            Map<String,MonthOrderQuantitySDO> mmm = newList.stream().collect(Collectors.toMap(MonthOrderQuantitySDO::getGmtCreateDate, Function.identity(),(v1,v2)->v1));
            result.put(orgId,mmm);
        }
        return result;
    }

    //获取调拨单明细数据
    private List<MonthOrderQuantitySDO> getAllocateOrderList(JobInitParam jobInitParam){
        List<Future<List<MonthOrderQuantitySDO>>> futureList = Lists.newArrayList();
        int total = getAllocateOrderListTotal(jobInitParam);
        int totalPage = (total + PageSize_500 - 1)/PageSize_500;
        for (int pageNo = 0; pageNo < totalPage; pageNo++) {
            int start = pageNo*PageSize_500;
            CompletableFuture<List<MonthOrderQuantitySDO>> future = CompletableFuture.supplyAsync(() -> {
                CommPageQueryRequest queryRequest = new CommPageQueryRequest();
                queryRequest.setOrganizationIds(Lists.newArrayList(jobInitParam.getCommerceCompanyOrg().getId()));
                queryRequest.setBeginDate(DomUtil.getStartOfMonth(DateUtils.parse(jobInitParam.getOneMonthAgo()))+" 00:00:00");
                queryRequest.setEndDate(jobInitParam.getToday()+" 23:59:59");
                queryRequest.setStart(start);
                queryRequest.setLimit(PageSize_500);
                Result<List<MonthOrderQuantitySDO>> result = null;
                try {
                    //log.info("pageQueryContractMoney_queryRequest={}", JSON.toJSONString(queryRequest));
                    result = allocateOrderDetailRepository.pageQueryAllocateOrderList(queryRequest);
                    if (result==null || CollectionUtils.isEmpty(result.getResult())){
                        return Lists.newArrayList();
                    }
                } catch (Exception e) {
                    log.error("多线程拉取调拨单明细数据异常", e);
                    return Lists.newArrayList();
                }
                return result.getResult();
            }, monthSalesReportTaskExecutor);
            futureList.add(future);
        }
        List<MonthOrderQuantitySDO> result = new ArrayList<>();
        try {
            for (Future< List<MonthOrderQuantitySDO>> future : futureList){
                List<MonthOrderQuantitySDO> subList = future.get();
                result.addAll(subList);
            }
        }catch (Exception e){
            log.error("获取多线程查询结果异常", e);
        }
        //log.info("executeGenerateMonthSalesBasicReport_getPlanContractDataList_size={}", result.size());
        //调拨单明细填充 分组字段
        List<String> warehouseIds = result.stream().map(MonthOrderQuantitySDO::getReceiveWarehouseId).collect(Collectors.toList());
        Map<String, WmsSDO> warehouseMap = baseDataQueryRepository.batchQueryWmsByIds(warehouseIds);
        List<String> addressIds = result.stream().map(MonthOrderQuantitySDO::getCustomerAddressId).collect(Collectors.toList());
        Map<String, CustomerAddressSDO> addressMap = baseDataQueryRepository.batchQueryCustomerAddress(addressIds);

        List ids = addressMap.values().stream().map(x ->{
            return x.getCommerceSellerCode()+"#"+x.getCommerceDeliveryCode();
        }).collect(Collectors.toList());
        Map<String, CustomerAddressSDO> commerceAddressMap = baseDataQueryRepository.batchQueryCustomerAddressByCondition(ids,jobInitParam.getCommerceSalesOrg().getId());

        for (MonthOrderQuantitySDO sdo:result) {
            if(sdo.getIsZF() != null && sdo.getIsZF()){
                sdo.setType("b");
                CustomerAddressSDO addressSDO = addressMap.get(sdo.getCustomerAddressId());
                if(addressSDO !=null && commerceAddressMap.get(addressSDO.getCommerceSellerCode()+"#"+addressSDO.getCommerceDeliveryCode()) !=null ){
                    CustomerAddressSDO commerceAddressSDO = commerceAddressMap.get(addressSDO.getCommerceSellerCode()+"#"+addressSDO.getCommerceDeliveryCode());
                    sdo.setOrganizationId(commerceAddressSDO.getOrgSaleChannelCode());
                    sdo.setPlatformId(commerceAddressSDO.getCommercePlatform());
                }
            }else{
                sdo.setType("B");
                WmsSDO wmsSDO = warehouseMap.get(sdo.getReceiveWarehouseId());
                if(wmsSDO != null){
                    //wmsSDO.getSapSalesOrgId() 赋值的是销售渠道组织id
                    sdo.setOrganizationId(wmsSDO.getSapSalesOrgId());
                    //wmsSDO.getFactoryCode() 赋值的是平台id
                    sdo.setPlatformId(wmsSDO.getFactoryCode());
                }
            }
        }
        List<String> platformIds = result.stream().filter(x -> "B".equals(x.getType())).map(MonthOrderQuantitySDO::getPlatformId).collect(Collectors.toList());
        Map<String, PlatformSDO> platformMap = baseDataQueryRepository.batchQueryPlatformsByIds(platformIds);
        result = result.stream().map(x->{
            if("B".equals(x.getType()) && StringUtil.isNotEmpty(x.getPlatformId())){
                PlatformSDO platformSDO = platformMap.get(x.getPlatformId());
                x.setPlatformId(platformSDO.getPlatformCode());
            }
            return x;
        }).collect(Collectors.toList());
        return result;
    }

    //获取调拨单明细总数
    private int getAllocateOrderListTotal(JobInitParam jobInitParam){
        CommPageQueryRequest queryRequest = new CommPageQueryRequest();
        queryRequest.setOrganizationIds(Lists.newArrayList(jobInitParam.getCommerceCompanyOrg().getId()));
        queryRequest.setBeginDate(DomUtil.getStartOfMonth(DateUtils.parse(jobInitParam.getOneMonthAgo()))+" 00:00:00");
        queryRequest.setEndDate(jobInitParam.getToday()+" 23:59:59");
        queryRequest.setStart(0);
        queryRequest.setLimit(1);
        Result<List<MonthOrderQuantitySDO>> orderPageResult = allocateOrderDetailRepository.pageQueryAllocateOrderList(queryRequest);
        return orderPageResult.getTotal();
    }

    private void computePlanTaskMoney(OrgMonthPlanQuantitySDO sdo,
                                      Map<String,List<OrgMonthPlanQuantitySDO>> adjustQuantityMap,
                                      Map<String,OrgMonthPlanQuantitySDO> taskQuantityMap,
                                      Map<String,SalesPlanScItem> scItemPriceMap){
        String key = sdo.getOrganizationId()+"-"+sdo.getScItemId();
        List<OrgMonthPlanQuantitySDO> companyAdjustScItemList = adjustQuantityMap.get(sdo.getOrganizationId());
        List<OrgMonthPlanQuantitySDO> adjustScItemList = Nullable.stream(companyAdjustScItemList).filter(x -> x.getScItemId().equals(sdo.getScItemId())).collect(Collectors.toList());
        SalesPlanScItem planScItem = scItemPriceMap.get(key);
        BigDecimal outboundPrice = planScItem!=null&&planScItem.getOutboundPrice()!=null?new BigDecimal(planScItem.getOutboundPrice()).divide(new BigDecimal(100)):new BigDecimal(0);
        //多次调整
        if(adjustScItemList.size()>1){
            adjustScItemList = adjustScItemList.stream().sorted((s1,s2) -> new BigDecimal(DateUtils.dateToStamp(s2.getGmtCreate())).compareTo(new BigDecimal(DateUtils.dateToStamp(s1.getGmtCreate())))).collect(Collectors.toList());
            OrgMonthPlanQuantitySDO recentAdjust = adjustScItemList.get(0);
            OrgMonthPlanQuantitySDO beforeAdjust = adjustScItemList.get(1);
            sdo.setMonthFirstTaskMoney(new BigDecimal(beforeAdjust.getMonthFirstTaskCount()+recentAdjust.getMonthFirstAdjustReturnCount()).multiply(outboundPrice));
            sdo.setMonthMiddleTaskMoney(new BigDecimal(beforeAdjust.getMonthMiddleTaskCount()+recentAdjust.getMonthMiddleAdjustReturnCount()).multiply(outboundPrice));
            sdo.setMonthLastTaskMoney(new BigDecimal(beforeAdjust.getMonthLastTaskCount()+recentAdjust.getMonthLastAdjustReturnCount()).multiply(outboundPrice));
        //一次调整
        }else if(adjustScItemList.size()==1){
            OrgMonthPlanQuantitySDO task = taskQuantityMap.get(key);
            OrgMonthPlanQuantitySDO adjust = adjustScItemList.get(0);
            sdo.setMonthFirstTaskMoney(new BigDecimal(task.getMonthFirstTaskCount()+adjust.getMonthFirstAdjustReturnCount()).multiply(outboundPrice));
            sdo.setMonthMiddleTaskMoney(new BigDecimal(task.getMonthMiddleTaskCount()+adjust.getMonthMiddleAdjustReturnCount()).multiply(outboundPrice));
            sdo.setMonthLastTaskMoney(new BigDecimal(task.getMonthLastTaskCount()+adjust.getMonthLastAdjustReturnCount()).multiply(outboundPrice));
        }else{
            sdo.setMonthFirstTaskMoney(new BigDecimal(sdo.getMonthFirstReturnCount()).multiply(outboundPrice));
            sdo.setMonthMiddleTaskMoney(new BigDecimal(sdo.getMonthMiddleReturnCount()).multiply(outboundPrice));
            sdo.setMonthLastTaskMoney(new BigDecimal(sdo.getMonthLastReturnCount()).multiply(outboundPrice));
        }
    }

    private OrderProgressMonitorReportSDO convertAndCountOrderComplete(JobInitParam jobInitParam, OrgMonthPlanQuantitySDO sdo,
                                                                       Map<String, OrganizationSDO> orgInfoMap,
                                                                       Map<String, BigDecimal> contractQuantityMap,
                                                                       BigDecimal orderQuantity,
                                                                       BigDecimal accumulativeOrderQuantity,
                                                                       Integer orgType){
        OrderProgressMonitorReportSDO bean = new OrderProgressMonitorReportSDO();
        bean.setOrganizationId(sdo.getOrganizationId());
        bean.setBizType(orgType);
        bean.setStatisticalDate(jobInitParam.getToday());
        OrganizationSDO org = orgInfoMap.get(sdo.getOrganizationId());
        //填充组织信息
        if(org != null){
            bean.setOrganizationName(org.getName());
            bean.setOrganizationCode(org.getCode());
            bean.setParentOrganizationId(org.getParentId());
        }

        BigDecimal monthFirstTaskMoney = sdo.getMonthFirstTaskMoney()!=null?sdo.getMonthFirstTaskMoney():new BigDecimal(0);
        monthFirstTaskMoney = monthFirstTaskMoney.setScale(2);
        BigDecimal monthMiddleTaskMoney = sdo.getMonthMiddleTaskMoney()!=null?sdo.getMonthMiddleTaskMoney():new BigDecimal(0);
        monthMiddleTaskMoney = monthMiddleTaskMoney.setScale(2);
        BigDecimal monthLastTaskMoney = sdo.getMonthLastTaskMoney()!=null?sdo.getMonthLastTaskMoney():new BigDecimal(0);
        monthLastTaskMoney = monthLastTaskMoney.setScale(2);

        //方法入参 orderQuantity  accumulativeOrderQuantity
        //合同量金额
        BigDecimal contractQuantity = contractQuantityMap.get(sdo.getOrganizationId())!=null?contractQuantityMap.get(sdo.getOrganizationId()):new BigDecimal(0);
        //全月任务金额
        BigDecimal replyQuantity = monthFirstTaskMoney.add(monthMiddleTaskMoney).add(monthLastTaskMoney);

        //计算月计划日均金额
        BigDecimal planDailyAverageQuantity = new BigDecimal(0);
        if("early".equals(jobInitParam.getWhenOfMonth())){
            planDailyAverageQuantity = monthFirstTaskMoney.divide(new BigDecimal(10),2,BigDecimal.ROUND_HALF_UP);
        }else if("middle".equals(jobInitParam.getWhenOfMonth())){
            planDailyAverageQuantity = (monthFirstTaskMoney.add(monthMiddleTaskMoney))
                    .divide(new BigDecimal(20),2,BigDecimal.ROUND_HALF_UP);
        }else if("late".equals(jobInitParam.getWhenOfMonth())){
            planDailyAverageQuantity = replyQuantity.divide(new BigDecimal(jobInitParam.getDaysOfMonth()),2,BigDecimal.ROUND_HALF_UP);
        }

        //预期总下单量
        BigDecimal expectedTotalOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(jobInitParam.getDays()));
        //当日应下单量  正数:计划还未完成，负数:计划已超额完成
        BigDecimal shouldOrderQuantity = expectedTotalOrderQuantity.subtract(accumulativeOrderQuantity);
        //当日差额  当日订单金额-当日应下单量    正数,负数
        BigDecimal differQuantity = orderQuantity.subtract(shouldOrderQuantity);

        //当日达成率 未完成:当日订单金额/当日应下单量  超额完成: 展示"-"
        BigDecimal completeRate = null;
        if(shouldOrderQuantity.compareTo(BigDecimal.ZERO) == 1){
            completeRate = orderQuantity.divide(shouldOrderQuantity,4,BigDecimal.ROUND_HALF_UP);
        }else{
            completeRate = new BigDecimal("-1");
            //completeRate = dayOrderQuantity.compareTo(BigDecimal.ZERO) == 1?differQuantity.divide(dayOrderQuantity,4,BigDecimal.ROUND_HALF_UP):new BigDecimal(0);
        }

        //本月达成率 累计订单量/当月任务量
        BigDecimal monthCompleteRate = replyQuantity.compareTo(BigDecimal.ZERO) == 0?
                new BigDecimal(-1):accumulativeOrderQuantity.divide(replyQuantity,4,BigDecimal.ROUND_HALF_UP);

        //填充数据
        bean.setMonthFirstTaskMoney(monthFirstTaskMoney);
        bean.setMonthMiddleTaskMoney(monthMiddleTaskMoney);
        bean.setMonthLastTaskMoney(monthLastTaskMoney);
        bean.setPlanDailyAverage(planDailyAverageQuantity);
        bean.setExpectedTotalOrderQuantity(expectedTotalOrderQuantity);
        bean.setShouldOrderQuantity(shouldOrderQuantity);
        bean.setOrderQuantity(orderQuantity);
        bean.setCompleteRate(completeRate);
        bean.setDifferQuantity(differQuantity);
        bean.setTaskQuantity(contractQuantity);
        bean.setReplyQuantity(replyQuantity);
        bean.setAccumulativeOrderQuantity(accumulativeOrderQuantity);
        bean.setMonthCompleteRate(monthCompleteRate);
        return bean;
    }

    private List<OrderProgressMonitorReportSDO> convertAndCountOrderComplete2(JobInitParam jobInitParam, Map<String, OrganizationSDO> companyOrgMap,
                                                                        Map<String, List<OrgMonthPlanQuantitySDO>> planScItemMap,
                                                                        Map<String, List<SalesPlanScItem>> scItemPriceMap,
                                                                        Map<String, Map<String,BigDecimal>> orderAmountMap,
                                                                        Map<String, BigDecimal> contractQuantityMap){
        List<OrderProgressMonitorReportSDO> result = new ArrayList<>();
        for (Map.Entry<String, OrganizationSDO> entryOrg: companyOrgMap.entrySet()){
            OrderProgressMonitorReportSDO bean = new OrderProgressMonitorReportSDO();
            OrganizationSDO org = entryOrg.getValue();
            //填充组织信息
            bean.setOrganizationId(org.getId());
            bean.setOrganizationName(org.getName());
            bean.setOrganizationCode(org.getCode());
            bean.setParentOrganizationId(org.getParentId());
            bean.setBizType(103);
            bean.setStatisticalDate(jobInitParam.getToday());

            List<OrgMonthPlanQuantitySDO> scItemDetail = planScItemMap.get(org.getId());
            //无计划跳过
            if(CollectionUtils.isEmpty(scItemDetail)){
                continue;
            }
            List<SalesPlanScItem> orgScItemPrice = scItemPriceMap.get(org.getId());
            Map<String,Long> orgScItemPriceMap = Nullable.stream(orgScItemPrice).collect(Collectors.toMap(SalesPlanScItem::getScItemId,x -> x.getOutboundPrice()!=null?x.getOutboundPrice():0L,(v1,v2)->v1));

            //计划货品维度  计算价格合并计划金额
            for(OrgMonthPlanQuantitySDO x:scItemDetail){
                BigDecimal price = orgScItemPriceMap.get(x.getScItemId()) != null?new BigDecimal(orgScItemPriceMap.get(x.getScItemId())).divide(new BigDecimal(100)):new BigDecimal(0);
                x.setFirstWeekConfirmMoney(new BigDecimal(x.getFirstWeekConfirmCount()!=null?x.getFirstWeekConfirmCount():0L).multiply(price));
                x.setSecondWeekConfirmMoney(new BigDecimal(x.getSecondWeekConfirmCount()!=null?x.getSecondWeekConfirmCount():0L).multiply(price));
                x.setThirdWeekConfirmMoney(new BigDecimal(x.getThirdWeekConfirmCount()!=null?x.getThirdWeekConfirmCount():0L).multiply(price));
                x.setFourthWeekConfirmMoney(new BigDecimal(x.getFourthWeekConfirmCount()!=null?x.getFourthWeekConfirmCount():0L).multiply(price));
            };
            BigDecimal firstWeekConfirmMoney = scItemDetail.stream().map(OrgMonthPlanQuantitySDO::getFirstWeekConfirmMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
            BigDecimal secondWeekConfirmMoney = scItemDetail.stream().map(OrgMonthPlanQuantitySDO::getSecondWeekConfirmMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
            BigDecimal thirdWeekConfirmMoney = scItemDetail.stream().map(OrgMonthPlanQuantitySDO::getThirdWeekConfirmMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
            BigDecimal fourthWeekConfirmMoney = scItemDetail.stream().map(OrgMonthPlanQuantitySDO::getFourthWeekConfirmMoney).reduce(BigDecimal.ZERO,BigDecimal::add);

            Map<String,BigDecimal> orderAmount = orderAmountMap.get(org.getId())!=null?orderAmountMap.get(org.getId()):new HashMap<>();
            //日订单金额
            BigDecimal orderQuantity = orderAmount.get(ORDER_QUANTITY)!=null?orderAmount.get(ORDER_QUANTITY):new BigDecimal(0);
            //累计订单金额
            BigDecimal accumulativeOrderQuantity = orderAmount.get(ACCUMULATIVE_ORDER_QUANTITY)!=null?orderAmount.get(ACCUMULATIVE_ORDER_QUANTITY):new BigDecimal(0);
            //合同量
            BigDecimal contractQuantity = contractQuantityMap.get(org.getId())!=null?contractQuantityMap.get(org.getId()):new BigDecimal(0);
            //全月任务数量
            BigDecimal replyQuantity = firstWeekConfirmMoney.add(secondWeekConfirmMoney).add(thirdWeekConfirmMoney).add(fourthWeekConfirmMoney);

            //计算月计划日均金额
            BigDecimal planDailyAverageQuantity = new BigDecimal(0);
            int day = jobInitParam.getDays();
            if( 1 <= day && 8 > day ){
                planDailyAverageQuantity = firstWeekConfirmMoney.divide(new BigDecimal(7),2,BigDecimal.ROUND_HALF_UP);
            }else if( 8 <= day && 15 > day ){
                planDailyAverageQuantity = (firstWeekConfirmMoney.add(secondWeekConfirmMoney))
                        .divide(new BigDecimal(14),2,BigDecimal.ROUND_HALF_UP);
            }else if( 15 <= day && 22 > day ){
                planDailyAverageQuantity = (firstWeekConfirmMoney.add(secondWeekConfirmMoney).add(thirdWeekConfirmMoney))
                        .divide(new BigDecimal(21),2,BigDecimal.ROUND_HALF_UP);
            }else if( 22 <= day){
                planDailyAverageQuantity = replyQuantity.divide(new BigDecimal(28),2,BigDecimal.ROUND_HALF_UP);
            }

            //预期总下单量
            BigDecimal expectedTotalOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(jobInitParam.getDays()));
            //当日应下单量  正数:计划还未完成，负数:计划已超额完成
            BigDecimal shouldOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(jobInitParam.getDays())).subtract(accumulativeOrderQuantity);
            //当日差额  当日订单金额-当日应下单量    正数,负数
            BigDecimal differQuantity = orderQuantity.subtract(shouldOrderQuantity);
            //当日达成率 未完成:当日订单金额/当日应下单量  超额完成: 展示"-"
            BigDecimal completeRate = null;
            if(shouldOrderQuantity.compareTo(BigDecimal.ZERO) == 1){
                completeRate = orderQuantity.divide(shouldOrderQuantity,4,BigDecimal.ROUND_HALF_UP);
            }else{
                completeRate = new BigDecimal("-1");
            }
            //本月达成率 累计订单量/当月任务量
            BigDecimal monthCompleteRate = replyQuantity.compareTo(BigDecimal.ZERO) == 0?
                    new BigDecimal(-1):accumulativeOrderQuantity.divide(replyQuantity,4,BigDecimal.ROUND_HALF_UP);

            //填充数据
            bean.setMonthFirstTaskMoney(firstWeekConfirmMoney);
            bean.setMonthMiddleTaskMoney(secondWeekConfirmMoney);
            bean.setMonthLastTaskMoney(thirdWeekConfirmMoney.add(fourthWeekConfirmMoney));
            bean.setMonthLastTaskMoney2(fourthWeekConfirmMoney);
            bean.setExpectedTotalOrderQuantity(expectedTotalOrderQuantity);
            bean.setPlanDailyAverage(planDailyAverageQuantity);
            bean.setShouldOrderQuantity(shouldOrderQuantity);
            bean.setOrderQuantity(orderQuantity);
            bean.setCompleteRate(completeRate);
            bean.setDifferQuantity(differQuantity);
            bean.setTaskQuantity(contractQuantity);
            bean.setReplyQuantity(replyQuantity);
            bean.setAccumulativeOrderQuantity(accumulativeOrderQuantity);
            bean.setMonthCompleteRate(monthCompleteRate);
            result.add(bean);
        }
        return result;
    }

    @FacadeInvoker
    private List<OrderProgressMonitorReportSDO> convertAndCountOrderComplete3(JobInitParam jobInitParam, Map<String, OrganizationSDO> orgCodeMap,
                                                                              Map<String, List<OrgMonthPlanQuantitySDO>> planScItemMap,
                                                                              Map<String, List<SalesPlanScItem>> scItemPriceMap,
                                                                              Map<String, BigDecimal> orderAmount,
                                                                              Map<String, BigDecimal> contractQuantityMap,
                                                                              Map<String, ScItemSDO> scItemMap,
                                                                              Integer orgType){
        List<OrderProgressMonitorReportSDO> result = new ArrayList<>();
        for (Map.Entry<String, OrganizationSDO> entryOrg: orgCodeMap.entrySet()){
            OrderProgressMonitorReportSDO bean = new OrderProgressMonitorReportSDO();
            OrganizationSDO org = entryOrg.getValue();
            //填充组织信息
            bean.setOrganizationId(org.getId());
            bean.setOrganizationName(org.getName());
            bean.setOrganizationCode(org.getCode());
            bean.setParentOrganizationId(org.getParentId());
            bean.setBizType(orgType);
            bean.setStatisticalDate(jobInitParam.getToday());

            List<OrgMonthPlanQuantitySDO> scItemDetail = planScItemMap.get(org.getId());
            //无计划跳过
            if(CollectionUtils.isEmpty(scItemDetail)){
                continue;
            }
            List<SalesPlanScItem> orgScItemPrice = scItemPriceMap.get(org.getId());
            Map<String,Long> orgScItemPriceMap = Nullable.stream(orgScItemPrice).collect(Collectors.toMap(SalesPlanScItem::getScItemId,x -> x.getOutboundPrice()!=null?x.getOutboundPrice():0L,(v1,v2)->v1));

            //计划货品维度  计算价格合并计划金额
            for(OrgMonthPlanQuantitySDO x:scItemDetail){
                if(scItemMap.get(x.getScItemId())!=null){
                    String scItemId = scItemMap.get(x.getScItemId()).getScItemId();
                    BigDecimal price = orgScItemPriceMap.get(scItemId) != null?new BigDecimal(orgScItemPriceMap.get(scItemId)).divide(new BigDecimal(100)):new BigDecimal(0);
                    x.setMonthFirstTaskMoney(new BigDecimal(x.getMonthFirstTaskCount()!=null?x.getMonthFirstTaskCount():0L).multiply(price));
                    x.setMonthMiddleTaskMoney(new BigDecimal(x.getMonthMiddleTaskCount()!=null?x.getMonthMiddleTaskCount():0L).multiply(price));
                    x.setMonthLastTaskMoney(new BigDecimal(x.getMonthLastTaskCount()!=null?x.getMonthLastTaskCount():0L).multiply(price));
                }else{
                    x.setMonthFirstTaskMoney(new BigDecimal(0));
                    x.setMonthMiddleTaskMoney(new BigDecimal(0));
                    x.setMonthLastTaskMoney(new BigDecimal(0));
                    log.warn("<电商销售组织订单监控>commerce_calculate_plan_money_query_scItemId_is_null,{}", x.getScItemId());
                }
            };
            BigDecimal monthFirstTaskMoney = scItemDetail.stream().map(OrgMonthPlanQuantitySDO::getMonthFirstTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
            BigDecimal monthMiddleTaskMoney = scItemDetail.stream().map(OrgMonthPlanQuantitySDO::getMonthMiddleTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
            BigDecimal monthLastTaskMoney = scItemDetail.stream().map(OrgMonthPlanQuantitySDO::getMonthLastTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add);

            //日订单金额
            BigDecimal orderQuantity = orderAmount.get(ORDER_QUANTITY)!=null?orderAmount.get(ORDER_QUANTITY):new BigDecimal(0);
            //累计订单金额
            BigDecimal accumulativeOrderQuantity = orderAmount.get(ACCUMULATIVE_ORDER_QUANTITY)!=null?orderAmount.get(ACCUMULATIVE_ORDER_QUANTITY):new BigDecimal(0);
            //合同量
            BigDecimal contractQuantity = contractQuantityMap.get(org.getId())!=null?contractQuantityMap.get(org.getId()):new BigDecimal(0);
            //全月任务数量
            BigDecimal replyQuantity = monthFirstTaskMoney.add(monthMiddleTaskMoney).add(monthLastTaskMoney);

            //计算月计划日均金额
            BigDecimal planDailyAverageQuantity = new BigDecimal(0);
            if("early".equals(jobInitParam.getWhenOfMonth())){
                planDailyAverageQuantity = monthFirstTaskMoney.divide(new BigDecimal(10),2,BigDecimal.ROUND_HALF_UP);
            }else if("middle".equals(jobInitParam.getWhenOfMonth())){
                planDailyAverageQuantity = (monthFirstTaskMoney.add(monthMiddleTaskMoney))
                        .divide(new BigDecimal(20),2,BigDecimal.ROUND_HALF_UP);
            }else if("late".equals(jobInitParam.getWhenOfMonth())){
                planDailyAverageQuantity = replyQuantity.divide(new BigDecimal(jobInitParam.getDaysOfMonth()),2,BigDecimal.ROUND_HALF_UP);
            }

            //预期总下单量
            BigDecimal expectedTotalOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(jobInitParam.getDays()));
            //当日应下单量  正数:计划还未完成，负数:计划已超额完成
            BigDecimal shouldOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(jobInitParam.getDays())).subtract(accumulativeOrderQuantity);
            //当日差额  当日订单金额-当日应下单量    正数,负数
            BigDecimal differQuantity = orderQuantity.subtract(shouldOrderQuantity);
            //当日达成率 未完成:当日订单金额/当日应下单量  超额完成: 展示"-"
            BigDecimal completeRate = null;
            if(shouldOrderQuantity.compareTo(BigDecimal.ZERO) == 1){
                completeRate = orderQuantity.divide(shouldOrderQuantity,4,BigDecimal.ROUND_HALF_UP);
            }else{
                completeRate = new BigDecimal("-1");
            }
            //本月达成率 累计订单量/当月任务量
            BigDecimal monthCompleteRate = replyQuantity.compareTo(BigDecimal.ZERO) == 0?
                    new BigDecimal(-1):accumulativeOrderQuantity.divide(replyQuantity,4,BigDecimal.ROUND_HALF_UP);

            //填充数据
            bean.setMonthFirstTaskMoney(monthFirstTaskMoney);
            bean.setMonthMiddleTaskMoney(monthMiddleTaskMoney);
            bean.setMonthLastTaskMoney(monthLastTaskMoney);
            bean.setExpectedTotalOrderQuantity(expectedTotalOrderQuantity);
            bean.setPlanDailyAverage(planDailyAverageQuantity);
            bean.setShouldOrderQuantity(shouldOrderQuantity);
            bean.setOrderQuantity(orderQuantity);
            bean.setCompleteRate(completeRate);
            bean.setDifferQuantity(differQuantity);
            bean.setTaskQuantity(contractQuantity);
            bean.setReplyQuantity(replyQuantity);
            bean.setAccumulativeOrderQuantity(accumulativeOrderQuantity);
            bean.setMonthCompleteRate(monthCompleteRate);
            result.add(bean);
        }
        return result;
    }

    private List<OrderProgressMonitorReportSDO> convertAndCountOrderComplete4(JobInitParam jobInitParam, OrganizationSDO companyOrg,
                                                                              Map<String, Map<String, BigDecimal>> companyOrderReport,
                                                                              Map<String, BigDecimal> contractQuantityMap,
                                                                              Integer orgType){
        List<OrderProgressMonitorReportSDO> result = new ArrayList<>();
        OrderProgressMonitorReportSDO bean = new OrderProgressMonitorReportSDO();
        String orgId = companyOrg.getId();
        //填充组织信息
        bean.setOrganizationId(orgId);
        bean.setOrganizationName(companyOrg.getName());
        bean.setOrganizationCode(companyOrg.getCode());
        bean.setParentOrganizationId(companyOrg.getParentId());
        bean.setBizType(orgType);
        bean.setStatisticalDate(jobInitParam.getToday());

        Map<String, BigDecimal> orderQuantityMap = companyOrderReport.get(ORDER_QUANTITY);
        Map<String, BigDecimal> accumulativeOrderQuantityMap = companyOrderReport.get(ACCUMULATIVE_ORDER_QUANTITY);
        Map<String, BigDecimal> monthFirstTaskMoneyMap = companyOrderReport.get(MONTH_FIRST_TASK_MONEY);
        Map<String, BigDecimal> monthMiddleTaskMoneyMap = companyOrderReport.get(MONTH_MIDDLE_TASK_MONEY);
        Map<String, BigDecimal> monthLastTaskMoneyMap = companyOrderReport.get(MONTH_LAST_TASK_MONEY);

        //订单量
        BigDecimal orderQuantity = orderQuantityMap.get(orgId)!=null?orderQuantityMap.get(orgId):new BigDecimal(0);
        //累计订单量
        BigDecimal accumulativeOrderQuantity = accumulativeOrderQuantityMap.get(orgId)!=null?accumulativeOrderQuantityMap.get(orgId):new BigDecimal(0);
        //上旬任务金额
        BigDecimal monthFirstTaskMoney = monthFirstTaskMoneyMap.get(orgId)!=null?monthFirstTaskMoneyMap.get(orgId):new BigDecimal(0);
        //中旬任务金额
        BigDecimal monthMiddleTaskMoney = monthMiddleTaskMoneyMap.get(orgId)!=null?monthMiddleTaskMoneyMap.get(orgId):new BigDecimal(0);
        //下旬任务金额
        BigDecimal monthLastTaskMoney = monthLastTaskMoneyMap.get(orgId)!=null?monthLastTaskMoneyMap.get(orgId):new BigDecimal(0);
        //合同量
        BigDecimal contractQuantity = contractQuantityMap.get(orgId)!=null?contractQuantityMap.get(orgId):new BigDecimal(0);
        //全月任务数量
        BigDecimal replyQuantity = monthFirstTaskMoney.add(monthMiddleTaskMoney).add(monthLastTaskMoney);

        //计算月计划日均金额
        BigDecimal planDailyAverageQuantity = new BigDecimal(0);
        if("early".equals(jobInitParam.getWhenOfMonth())){
            planDailyAverageQuantity = monthFirstTaskMoney.divide(new BigDecimal(10),2,BigDecimal.ROUND_HALF_UP);
        }else if("middle".equals(jobInitParam.getWhenOfMonth())){
            planDailyAverageQuantity = (monthFirstTaskMoney.add(monthMiddleTaskMoney))
                    .divide(new BigDecimal(20),2,BigDecimal.ROUND_HALF_UP);
        }else if("late".equals(jobInitParam.getWhenOfMonth())){
            planDailyAverageQuantity = replyQuantity.divide(new BigDecimal(jobInitParam.getDaysOfMonth()),2,BigDecimal.ROUND_HALF_UP);
        }

        //预期总下单量
        BigDecimal expectedTotalOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(jobInitParam.getDays()));
        //当日应下单量  正数:计划还未完成，负数:计划已超额完成
        BigDecimal shouldOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(jobInitParam.getDays())).subtract(accumulativeOrderQuantity);
        //当日差额  当日订单金额-当日应下单量    正数,负数
        BigDecimal differQuantity = orderQuantity.subtract(shouldOrderQuantity);
        //当日达成率 未完成:当日订单金额/当日应下单量  超额完成: 展示"-"
        BigDecimal completeRate = null;
        if(shouldOrderQuantity.compareTo(BigDecimal.ZERO) == 1){
            completeRate = orderQuantity.divide(shouldOrderQuantity,4,BigDecimal.ROUND_HALF_UP);
        }else{
            completeRate = new BigDecimal("-1");
        }
        //本月达成率 累计订单量/当月任务量
        BigDecimal monthCompleteRate = replyQuantity.compareTo(BigDecimal.ZERO) == 0?
                new BigDecimal(-1):accumulativeOrderQuantity.divide(replyQuantity,4,BigDecimal.ROUND_HALF_UP);

        //填充数据
        bean.setMonthFirstTaskMoney(monthFirstTaskMoney);
        bean.setMonthMiddleTaskMoney(monthMiddleTaskMoney);
        bean.setMonthLastTaskMoney(monthLastTaskMoney);
        bean.setExpectedTotalOrderQuantity(expectedTotalOrderQuantity);
        bean.setPlanDailyAverage(planDailyAverageQuantity);
        bean.setShouldOrderQuantity(shouldOrderQuantity);
        bean.setOrderQuantity(orderQuantity);
        bean.setCompleteRate(completeRate);
        bean.setDifferQuantity(differQuantity);
        bean.setTaskQuantity(contractQuantity);
        bean.setReplyQuantity(replyQuantity);
        bean.setAccumulativeOrderQuantity(accumulativeOrderQuantity);
        bean.setMonthCompleteRate(monthCompleteRate);
        result.add(bean);
        return result;
    }

    private List<OrderProgressMonitorReportSDO> convertAndCountOrderComplete5(JobInitParam jobInitParam, List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO> channelOrgList,
                                                                              Map<String, List<MonthlyPlanOfCcommerce>> channelPlanScItemMap,
                                                                              Map<String, List<SalesPlanScItem>> scItemPriceMap,
                                                                              Map<String, Map<String,MonthOrderQuantitySDO>> channelOrgQuantityMap,
                                                                              Map<String, BigDecimal> contractQuantityMap,
                                                                              Map<String, ScItemSDO> scItemMap,
                                                                              Integer orgType){
        List<OrderProgressMonitorReportSDO> result = new ArrayList<>();
        for (com.epoch.app.crplatformenhance.sdo.OrganizationSDO channelOrg:channelOrgList) {
            OrderProgressMonitorReportSDO bean = new OrderProgressMonitorReportSDO();
            String orgId = channelOrg.getId();
            //填充组织信息
            bean.setOrganizationId(orgId);
            bean.setOrganizationName(channelOrg.getName());
            bean.setOrganizationCode(channelOrg.getCode());
            bean.setParentOrganizationId(channelOrg.getParentId());
            bean.setBizType(orgType);
            bean.setStatisticalDate(jobInitParam.getToday());

            List<MonthlyPlanOfCcommerce> scItemDetail = channelPlanScItemMap.get(orgId);
            //无计划跳过
            if(CollectionUtils.isEmpty(scItemDetail)){
                continue;
            }
            List<SalesPlanScItem> orgScItemPrice = scItemPriceMap.get(orgId);
            Map<String,Long> orgScItemPriceMap = Nullable.stream(orgScItemPrice).collect(Collectors.toMap(SalesPlanScItem::getScItemId,x -> x.getOutboundPrice()!=null?x.getOutboundPrice():0L,(v1,v2)->v1));

            List<OrgMonthPlanQuantitySDO> scItemQuantityDetail = new ArrayList<>();
            //计划货品维度  计算价格合并计划金额
            for(MonthlyPlanOfCcommerce x:scItemDetail){
                if(scItemMap.get(x.getOuterId())!=null){
                    String scItemId = scItemMap.get(x.getOuterId()).getScItemId();
                    BigDecimal price = orgScItemPriceMap.get(scItemId) != null?new BigDecimal(orgScItemPriceMap.get(scItemId)).divide(new BigDecimal(100)):new BigDecimal(0);
                    OrgMonthPlanQuantitySDO sdo = new OrgMonthPlanQuantitySDO();
                    sdo.setOrganizationId(orgId);
                    sdo.setScItemId(scItemId);
                    sdo.setMonthFirstTaskMoney(new BigDecimal(x.getMonthFirstReviseConfirmCount()!=null?x.getMonthFirstReviseConfirmCount():0L).multiply(price));
                    sdo.setMonthMiddleTaskMoney(new BigDecimal(x.getMonthMiddleReviseConfirmCount()!=null?x.getMonthMiddleReviseConfirmCount():0L).multiply(price));
                    sdo.setMonthLastTaskMoney(new BigDecimal(x.getMonthLastReviseConfirmCount()!=null?x.getMonthLastReviseConfirmCount():0L).multiply(price));
                    scItemQuantityDetail.add(sdo);
                }else{
                    log.warn("<电商销售渠道订单监控>commerce_calculate_plan_money_query_scItemId_is_null,{}", x.getOuterId());
                }
            };
            BigDecimal monthFirstTaskMoney = scItemQuantityDetail.stream().map(OrgMonthPlanQuantitySDO::getMonthFirstTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
            BigDecimal monthMiddleTaskMoney = scItemQuantityDetail.stream().map(OrgMonthPlanQuantitySDO::getMonthMiddleTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
            BigDecimal monthLastTaskMoney = scItemQuantityDetail.stream().map(OrgMonthPlanQuantitySDO::getMonthLastTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add);

            Map<String,BigDecimal> orderAmount = getOrderQuantity(channelOrgQuantityMap,orgId,jobInitParam.getToday());
            //订单量
            BigDecimal orderQuantity = orderAmount.get(ORDER_QUANTITY)!=null?orderAmount.get(ORDER_QUANTITY):new BigDecimal(0);
            //累计订单量
            BigDecimal accumulativeOrderQuantity = orderAmount.get(ACCUMULATIVE_ORDER_QUANTITY)!=null?orderAmount.get(ACCUMULATIVE_ORDER_QUANTITY):new BigDecimal(0);
            //合同量
            BigDecimal contractQuantity = contractQuantityMap.get(orgId)!=null?contractQuantityMap.get(orgId):new BigDecimal(0);
            //全月任务数量
            BigDecimal replyQuantity = monthFirstTaskMoney.add(monthMiddleTaskMoney).add(monthLastTaskMoney);

            //计算月计划日均金额
            BigDecimal planDailyAverageQuantity = new BigDecimal(0);
            if("early".equals(jobInitParam.getWhenOfMonth())){
                planDailyAverageQuantity = monthFirstTaskMoney.divide(new BigDecimal(10),2,BigDecimal.ROUND_HALF_UP);
            }else if("middle".equals(jobInitParam.getWhenOfMonth())){
                planDailyAverageQuantity = (monthFirstTaskMoney.add(monthMiddleTaskMoney))
                        .divide(new BigDecimal(20),2,BigDecimal.ROUND_HALF_UP);
            }else if("late".equals(jobInitParam.getWhenOfMonth())){
                planDailyAverageQuantity = replyQuantity.divide(new BigDecimal(jobInitParam.getDaysOfMonth()),2,BigDecimal.ROUND_HALF_UP);
            }

            //预期总下单量
            BigDecimal expectedTotalOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(jobInitParam.getDays()));
            //当日应下单量  正数:计划还未完成，负数:计划已超额完成
            BigDecimal shouldOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(jobInitParam.getDays())).subtract(accumulativeOrderQuantity);
            //当日差额  当日订单金额-当日应下单量    正数,负数
            BigDecimal differQuantity = orderQuantity.subtract(shouldOrderQuantity);
            //当日达成率 未完成:当日订单金额/当日应下单量  超额完成: 展示"-"
            BigDecimal completeRate = null;
            if(shouldOrderQuantity.compareTo(BigDecimal.ZERO) == 1){
                completeRate = orderQuantity.divide(shouldOrderQuantity,4,BigDecimal.ROUND_HALF_UP);
            }else{
                completeRate = new BigDecimal("-1");
            }
            //本月达成率 累计订单量/当月任务量
            BigDecimal monthCompleteRate = replyQuantity.compareTo(BigDecimal.ZERO) == 0?
                    new BigDecimal(-1):accumulativeOrderQuantity.divide(replyQuantity,4,BigDecimal.ROUND_HALF_UP);

            //填充数据
            bean.setMonthFirstTaskMoney(monthFirstTaskMoney);
            bean.setMonthMiddleTaskMoney(monthMiddleTaskMoney);
            bean.setMonthLastTaskMoney(monthLastTaskMoney);
            bean.setExpectedTotalOrderQuantity(expectedTotalOrderQuantity);
            bean.setPlanDailyAverage(planDailyAverageQuantity);
            bean.setShouldOrderQuantity(shouldOrderQuantity);
            bean.setOrderQuantity(orderQuantity);
            bean.setCompleteRate(completeRate);
            bean.setDifferQuantity(differQuantity);
            bean.setTaskQuantity(contractQuantity);
            bean.setReplyQuantity(replyQuantity);
            bean.setAccumulativeOrderQuantity(accumulativeOrderQuantity);
            bean.setMonthCompleteRate(monthCompleteRate);
            result.add(bean);
        }
        return result;
    }

    private List<OrderProgressMonitorReportSDO> convertAndCountOrderComplete6(JobInitParam jobInitParam,
                                                                              Map<String, List<MonthlyPlanOfCcommerce>> platformPlanScItemMap,
                                                                              Map<String, List<SalesPlanScItem>> scItemPriceMap,
                                                                              Map<String, Map<String,MonthOrderQuantitySDO>> platformQuantityMap,
                                                                              Map<String, BigDecimal> contractQuantityMap,
                                                                              Map<String, ScItemSDO> scItemMap,
                                                                              Integer orgType){
        List<OrderProgressMonitorReportSDO> result = new ArrayList<>();
        for (Map.Entry<String, List<MonthlyPlanOfCcommerce>> entry: platformPlanScItemMap.entrySet()){
            List<MonthlyPlanOfCcommerce> scItemDetail = entry.getValue();
            //无计划跳过
            if(CollectionUtils.isEmpty(scItemDetail)){
                continue;
            }
            OrderProgressMonitorReportSDO bean = new OrderProgressMonitorReportSDO();
            String orgId = scItemDetail.get(0).getOrgSaleChannelCode();
            String platformCode = scItemDetail.get(0).getCommercePlatform();
            String platformName = scItemDetail.get(0).getOrgSaleDepartmentCode();
            //填充组织信息
            bean.setOrganizationId(platformCode);
            bean.setOrganizationName(platformName);
            bean.setParentOrganizationId(orgId);
            bean.setBizType(orgType);
            bean.setStatisticalDate(jobInitParam.getToday());

            List<SalesPlanScItem> orgScItemPrice = scItemPriceMap.get(orgId);
            Map<String,Long> orgScItemPriceMap = Nullable.stream(orgScItemPrice).collect(Collectors.toMap(SalesPlanScItem::getScItemId,x -> x.getOutboundPrice()!=null?x.getOutboundPrice():0L,(v1,v2)->v1));

            List<OrgMonthPlanQuantitySDO> scItemQuantityDetail = new ArrayList<>();
            //计划货品维度  计算价格合并计划金额
            for(MonthlyPlanOfCcommerce x:scItemDetail){
                if(scItemMap.get(x.getOuterId())!=null){
                    String scItemId = scItemMap.get(x.getOuterId()).getScItemId();
                    BigDecimal price = orgScItemPriceMap.get(scItemId) != null?new BigDecimal(orgScItemPriceMap.get(scItemId)).divide(new BigDecimal(100)):new BigDecimal(0);
                    OrgMonthPlanQuantitySDO sdo = new OrgMonthPlanQuantitySDO();
                    sdo.setOrganizationId(orgId);
                    sdo.setScItemId(scItemId);
                    sdo.setMonthFirstTaskMoney(new BigDecimal(x.getMonthFirstReviseConfirmCount()!=null?x.getMonthFirstReviseConfirmCount():0L).multiply(price));
                    sdo.setMonthMiddleTaskMoney(new BigDecimal(x.getMonthMiddleReviseConfirmCount()!=null?x.getMonthMiddleReviseConfirmCount():0L).multiply(price));
                    sdo.setMonthLastTaskMoney(new BigDecimal(x.getMonthLastReviseConfirmCount()!=null?x.getMonthLastReviseConfirmCount():0L).multiply(price));
                    scItemQuantityDetail.add(sdo);
                }else{
                    log.warn("<电商平台订单监控>commerce_calculate_plan_money_query_scItemId_is_null,{}", x.getOuterId());
                }
            };
            BigDecimal monthFirstTaskMoney = scItemQuantityDetail.stream().map(OrgMonthPlanQuantitySDO::getMonthFirstTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
            BigDecimal monthMiddleTaskMoney = scItemQuantityDetail.stream().map(OrgMonthPlanQuantitySDO::getMonthMiddleTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
            BigDecimal monthLastTaskMoney = scItemQuantityDetail.stream().map(OrgMonthPlanQuantitySDO::getMonthLastTaskMoney).reduce(BigDecimal.ZERO,BigDecimal::add);

            Map<String,BigDecimal> orderAmount = getOrderQuantity(platformQuantityMap,platformCode,jobInitParam.getToday());
            //订单量
            BigDecimal orderQuantity = orderAmount.get(ORDER_QUANTITY)!=null?orderAmount.get(ORDER_QUANTITY):new BigDecimal(0);
            //累计订单量
            BigDecimal accumulativeOrderQuantity = orderAmount.get(ACCUMULATIVE_ORDER_QUANTITY)!=null?orderAmount.get(ACCUMULATIVE_ORDER_QUANTITY):new BigDecimal(0);

            //合同量
            BigDecimal contractQuantity = contractQuantityMap.get(orgId)!=null?contractQuantityMap.get(orgId):new BigDecimal(0);
            //全月任务数量
            BigDecimal replyQuantity = monthFirstTaskMoney.add(monthMiddleTaskMoney).add(monthLastTaskMoney);

            //计算月计划日均金额
            BigDecimal planDailyAverageQuantity = new BigDecimal(0);
            if("early".equals(jobInitParam.getWhenOfMonth())){
                planDailyAverageQuantity = monthFirstTaskMoney.divide(new BigDecimal(10),2,BigDecimal.ROUND_HALF_UP);
            }else if("middle".equals(jobInitParam.getWhenOfMonth())){
                planDailyAverageQuantity = (monthFirstTaskMoney.add(monthMiddleTaskMoney))
                        .divide(new BigDecimal(20),2,BigDecimal.ROUND_HALF_UP);
            }else if("late".equals(jobInitParam.getWhenOfMonth())){
                planDailyAverageQuantity = replyQuantity.divide(new BigDecimal(jobInitParam.getDaysOfMonth()),2,BigDecimal.ROUND_HALF_UP);
            }

            //预期总下单量
            BigDecimal expectedTotalOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(jobInitParam.getDays()));
            //当日应下单量  正数:计划还未完成，负数:计划已超额完成
            BigDecimal shouldOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(jobInitParam.getDays())).subtract(accumulativeOrderQuantity);
            //当日差额  当日订单金额-当日应下单量    正数,负数
            BigDecimal differQuantity = orderQuantity.subtract(shouldOrderQuantity);
            //当日达成率 未完成:当日订单金额/当日应下单量  超额完成: 展示"-"
            BigDecimal completeRate = null;
            if(shouldOrderQuantity.compareTo(BigDecimal.ZERO) == 1){
                completeRate = orderQuantity.divide(shouldOrderQuantity,4,BigDecimal.ROUND_HALF_UP);
            }else{
                completeRate = new BigDecimal("-1");
            }
            //本月达成率 累计订单量/当月任务量
            BigDecimal monthCompleteRate = replyQuantity.compareTo(BigDecimal.ZERO) == 0?
                    new BigDecimal(-1):accumulativeOrderQuantity.divide(replyQuantity,4,BigDecimal.ROUND_HALF_UP);

            //填充数据
            bean.setMonthFirstTaskMoney(monthFirstTaskMoney);
            bean.setMonthMiddleTaskMoney(monthMiddleTaskMoney);
            bean.setMonthLastTaskMoney(monthLastTaskMoney);
            bean.setExpectedTotalOrderQuantity(expectedTotalOrderQuantity);
            bean.setPlanDailyAverage(planDailyAverageQuantity);
            bean.setShouldOrderQuantity(shouldOrderQuantity);
            bean.setOrderQuantity(orderQuantity);
            bean.setCompleteRate(completeRate);
            bean.setDifferQuantity(differQuantity);
            bean.setTaskQuantity(contractQuantity);
            bean.setReplyQuantity(replyQuantity);
            bean.setAccumulativeOrderQuantity(accumulativeOrderQuantity);
            bean.setMonthCompleteRate(monthCompleteRate);
            result.add(bean);
        }
        return result;
    }

    private void recountOrderComplete(OrderProgressMonitorReportSDO sdo,BigDecimal newOrderQuantity,BigDecimal newAccOrderQuantity){
        //月计划日均量
        //BigDecimal planDailyAverageQuantity = sdo.getPlanDailyAverage();
        //预期总下单量
        BigDecimal expectedTotalOrderQuantity = sdo.getExpectedTotalOrderQuantity()!=null?sdo.getExpectedTotalOrderQuantity():new BigDecimal(0);
        //合同量金额
        //BigDecimal contractQuantity = sdo.getTaskQuantity();
        //全月任务金额
        BigDecimal replyQuantity = sdo.getReplyQuantity();

        //当日应下单量  正数:计划还未完成，负数:计划已超额完成
        BigDecimal shouldOrderQuantity = expectedTotalOrderQuantity.subtract(newAccOrderQuantity);
        //当日差额  当日订单金额-当日应下单量    正数,负数
        BigDecimal differQuantity = newOrderQuantity.subtract(shouldOrderQuantity);

        //当日达成率 未完成:当日订单金额/当日应下单量  超额完成: 展示"-"
        BigDecimal completeRate = null;
        if(shouldOrderQuantity.compareTo(BigDecimal.ZERO) == 1){
            completeRate = newOrderQuantity.divide(shouldOrderQuantity,4,BigDecimal.ROUND_HALF_UP);
        }else{
            completeRate = new BigDecimal("-1");
            //completeRate = dayOrderQuantity.compareTo(BigDecimal.ZERO) == 1?differQuantity.divide(dayOrderQuantity,4,BigDecimal.ROUND_HALF_UP):new BigDecimal(0);
        }

        //本月达成率 累计订单量/当月任务量
        BigDecimal monthCompleteRate = replyQuantity.compareTo(BigDecimal.ZERO) == 0?
                new BigDecimal(-1):newAccOrderQuantity.divide(replyQuantity,4,BigDecimal.ROUND_HALF_UP);

        //填充数据
        sdo.setShouldOrderQuantity(shouldOrderQuantity);
        sdo.setOrderQuantity(newOrderQuantity);
        sdo.setCompleteRate(completeRate);
        sdo.setDifferQuantity(differQuantity);
        sdo.setAccumulativeOrderQuantity(newAccOrderQuantity);
        sdo.setMonthCompleteRate(monthCompleteRate);
    }

    private OrderProgressMonitorReportSDO recountCommercePlan(OrderProgressMonitorReportSDO oldReportBean,OrderProgressMonitorReportSDO newPlanSDO){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtils.parse(oldReportBean.getStatisticalDate()));
        int days = calendar.get(Calendar.DAY_OF_MONTH);
        int daysOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        //订单量
        BigDecimal orderQuantity = oldReportBean.getOrderQuantity();
        BigDecimal accumulativeOrderQuantity = oldReportBean.getAccumulativeOrderQuantity();
        //合同量金额
        BigDecimal contractQuantity = oldReportBean.getTaskQuantity();
        //上中下旬任务金额
        BigDecimal monthFirstTaskMoney = newPlanSDO.getMonthFirstTaskMoney();
        BigDecimal monthMiddleTaskMoney = newPlanSDO.getMonthMiddleTaskMoney();
        BigDecimal monthLastTaskMoney = newPlanSDO.getMonthLastTaskMoney();
        //全月任务金额
        BigDecimal replyQuantity = newPlanSDO.getReplyQuantity();

        //计算月计划日均金额
        BigDecimal planDailyAverageQuantity = new BigDecimal(0);
        if(days <= 10){
            planDailyAverageQuantity = monthFirstTaskMoney.divide(new BigDecimal(10),2,BigDecimal.ROUND_HALF_UP);
        }else if(days > 10 && days <= 20){
            planDailyAverageQuantity = (monthFirstTaskMoney.add(monthMiddleTaskMoney))
                    .divide(new BigDecimal(20),2,BigDecimal.ROUND_HALF_UP);
        }else if(days > 20){
            planDailyAverageQuantity = replyQuantity.divide(new BigDecimal(daysOfMonth),2,BigDecimal.ROUND_HALF_UP);
        }

        //预期总下单量
        BigDecimal expectedTotalOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(days));
        //当日应下单量  正数:计划还未完成，负数:计划已超额完成
        BigDecimal shouldOrderQuantity = expectedTotalOrderQuantity.subtract(accumulativeOrderQuantity);
        //当日差额  当日订单金额-当日应下单量    正数,负数
        BigDecimal differQuantity = orderQuantity.subtract(shouldOrderQuantity);

        //当日达成率 未完成:当日订单金额/当日应下单量  超额完成: 展示"-"
        BigDecimal completeRate = null;
        if(shouldOrderQuantity.compareTo(BigDecimal.ZERO) == 1){
            completeRate = orderQuantity.divide(shouldOrderQuantity,4,BigDecimal.ROUND_HALF_UP);
        }else{
            completeRate = new BigDecimal("-1");
        }

        //本月达成率 累计订单量/当月任务量
        BigDecimal monthCompleteRate = replyQuantity.compareTo(BigDecimal.ZERO) == 0?
                new BigDecimal(-1):accumulativeOrderQuantity.divide(replyQuantity,4,BigDecimal.ROUND_HALF_UP);

        //填充数据
        OrderProgressMonitorReportSDO bean = new OrderProgressMonitorReportSDO();
        bean.setOrganizationId(oldReportBean.getOrganizationId());
        bean.setBizType(oldReportBean.getBizType());
        bean.setStatisticalDate(oldReportBean.getStatisticalDate());
        bean.setMonthFirstTaskMoney(monthFirstTaskMoney);
        bean.setMonthMiddleTaskMoney(monthMiddleTaskMoney);
        bean.setMonthLastTaskMoney(monthLastTaskMoney);
        bean.setPlanDailyAverage(planDailyAverageQuantity);
        bean.setExpectedTotalOrderQuantity(expectedTotalOrderQuantity);
        bean.setShouldOrderQuantity(shouldOrderQuantity);
        bean.setOrderQuantity(orderQuantity);
        bean.setCompleteRate(completeRate);
        bean.setDifferQuantity(differQuantity);
        bean.setTaskQuantity(contractQuantity);
        bean.setReplyQuantity(replyQuantity);
        bean.setAccumulativeOrderQuantity(accumulativeOrderQuantity);
        bean.setMonthCompleteRate(monthCompleteRate);
        return bean;
    }

    private OrderProgressMonitorReportSDO recountNykPlan(OrderProgressMonitorReportSDO oldReportBean,OrderProgressMonitorReportSDO newPlanSDO){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtils.parse(oldReportBean.getStatisticalDate()));
        int days = calendar.get(Calendar.DAY_OF_MONTH);

        //订单量
        BigDecimal orderQuantity = oldReportBean.getOrderQuantity();
        BigDecimal accumulativeOrderQuantity = oldReportBean.getAccumulativeOrderQuantity();
        //合同量金额
        BigDecimal contractQuantity = oldReportBean.getTaskQuantity();
        //上中下旬任务金额
        BigDecimal firstWeekConfirmMoney = newPlanSDO.getMonthFirstTaskMoney();
        BigDecimal secondWeekConfirmMoney = newPlanSDO.getMonthMiddleTaskMoney();
        BigDecimal thirdWeekConfirmMoney = newPlanSDO.getMonthLastTaskMoney().subtract(newPlanSDO.getMonthLastTaskMoney2());
        BigDecimal fourthWeekConfirmMoney = newPlanSDO.getMonthLastTaskMoney2();
        //全月任务金额
        BigDecimal replyQuantity = newPlanSDO.getReplyQuantity();

        //计算月计划日均金额
        BigDecimal planDailyAverageQuantity = new BigDecimal(0);
        if( 1 <= days && 8 > days ){
            planDailyAverageQuantity = firstWeekConfirmMoney.divide(new BigDecimal(7),2,BigDecimal.ROUND_HALF_UP);
        }else if( 8 <= days && 15 > days ){
            planDailyAverageQuantity = (firstWeekConfirmMoney.add(secondWeekConfirmMoney))
                    .divide(new BigDecimal(14),2,BigDecimal.ROUND_HALF_UP);
        }else if( 15 <= days && 22 > days ){
            planDailyAverageQuantity = (firstWeekConfirmMoney.add(secondWeekConfirmMoney).add(thirdWeekConfirmMoney))
                    .divide(new BigDecimal(21),2,BigDecimal.ROUND_HALF_UP);
        }else if( 22 <= days){
            planDailyAverageQuantity = replyQuantity.divide(new BigDecimal(28),2,BigDecimal.ROUND_HALF_UP);
        }

        //预期总下单量
        BigDecimal expectedTotalOrderQuantity = planDailyAverageQuantity.multiply(new BigDecimal(days));
        //当日应下单量  正数:计划还未完成，负数:计划已超额完成
        BigDecimal shouldOrderQuantity = expectedTotalOrderQuantity.subtract(accumulativeOrderQuantity);
        //当日差额  当日订单金额-当日应下单量    正数,负数
        BigDecimal differQuantity = orderQuantity.subtract(shouldOrderQuantity);

        //当日达成率 未完成:当日订单金额/当日应下单量  超额完成: 展示"-"
        BigDecimal completeRate = null;
        if(shouldOrderQuantity.compareTo(BigDecimal.ZERO) == 1){
            completeRate = orderQuantity.divide(shouldOrderQuantity,4,BigDecimal.ROUND_HALF_UP);
        }else{
            completeRate = new BigDecimal("-1");
        }

        //本月达成率 累计订单量/当月任务量
        BigDecimal monthCompleteRate = replyQuantity.compareTo(BigDecimal.ZERO) == 0?
                new BigDecimal(-1):accumulativeOrderQuantity.divide(replyQuantity,4,BigDecimal.ROUND_HALF_UP);

        //填充数据
        OrderProgressMonitorReportSDO bean = new OrderProgressMonitorReportSDO();
        bean.setOrganizationId(oldReportBean.getOrganizationId());
        bean.setBizType(oldReportBean.getBizType());
        bean.setStatisticalDate(oldReportBean.getStatisticalDate());
        bean.setMonthFirstTaskMoney(firstWeekConfirmMoney);
        bean.setMonthMiddleTaskMoney(secondWeekConfirmMoney);
        bean.setMonthLastTaskMoney(thirdWeekConfirmMoney.add(fourthWeekConfirmMoney));
        bean.setPlanDailyAverage(planDailyAverageQuantity);
        bean.setExpectedTotalOrderQuantity(expectedTotalOrderQuantity);
        bean.setShouldOrderQuantity(shouldOrderQuantity);
        bean.setOrderQuantity(orderQuantity);
        bean.setCompleteRate(completeRate);
        bean.setDifferQuantity(differQuantity);
        bean.setTaskQuantity(contractQuantity);
        bean.setReplyQuantity(replyQuantity);
        bean.setAccumulativeOrderQuantity(accumulativeOrderQuantity);
        bean.setMonthCompleteRate(monthCompleteRate);
        return bean;
    }

    @FacadeInvoker
    private Map<String,OrderProgressMonitorReportSDO> queryOldReport(String statisticalDate){
        //查询总部订单监控报表 old数据
        QueryOrderMonitorReportRequest queryRequest = QueryOrderMonitorReportRequest.builder()
                .statisticalDate(statisticalDate)
                .limit(PageSize_500*2)
                .build();
        List<OrderProgressMonitorReportSDO> result = orderProgressMonitorReportQueryRepository.getOrderMonitorReportList(queryRequest);
        Map<String,OrderProgressMonitorReportSDO> resultMap = Nullable.stream(result).collect(Collectors.toMap(OrderProgressMonitorReportSDO::getOrganizationId,Function.identity(),(v1,v2)->v1));
        return resultMap;
    }

    @FacadeInvoker
    private Map<String,Object> getAction(OrderProgressMonitorReportSDO sdo,OrderProgressMonitorReportSDO oldSdo){
        Map<String,Object> resultMap = new HashMap<>();
        List<String> equalFields = Lists.newArrayList("monthFirstTaskMoney","monthMiddleTaskMoney","monthLastTaskMoney","planDailyAverage",
                "shouldOrderQuantity","orderQuantity","completeRate","differQuantity","taskQuantity","replyQuantity","accumulativeOrderQuantity","monthCompleteRate");
        if(oldSdo == null){
            resultMap.put("oldData",null);
            resultMap.put("action","add");
            return resultMap;
        }
        if(ObjectEqualsUtil.domainEquals(sdo, oldSdo, equalFields)){
            resultMap.put("oldData",oldSdo);
            resultMap.put("action","noAction");
        }else{
            resultMap.put("oldData",oldSdo);
            resultMap.put("action","update");
        }
        return resultMap;
    }

    private Map<String,BigDecimal> getOrderQuantity(Map<String,Map<String,MonthOrderQuantitySDO>> orderInfoMap,String orgId,String date){
        if(StringUtil.isBlank(orgId)){
            return new HashMap();
        }
        BigDecimal orderQuantity = new BigDecimal(0);
        BigDecimal accumulativeOrderQuantity = new BigDecimal(0);
        if(orderInfoMap.get(orgId)!=null && orderInfoMap.get(orgId).get(date)!=null){
            MonthOrderQuantitySDO monthOrderQuantitySDO = orderInfoMap.get(orgId).get(date);
            //当日订单金额
            orderQuantity = monthOrderQuantitySDO.getOrderAmount();
            //累计订单金额
            accumulativeOrderQuantity = monthOrderQuantitySDO.getAccumulativeOrderAmount();
        }
        Map<String,BigDecimal> result = new HashMap();
        result.put(ORDER_QUANTITY,orderQuantity);
        result.put(ACCUMULATIVE_ORDER_QUANTITY,accumulativeOrderQuantity);
        return result;
    }

    private Map<String,BigDecimal> getOrderQuantityByOrgIds(Map<String,Map<String,MonthOrderQuantitySDO>> orderInfoMap,List<String> orgIds,String date){
        if(CollectionUtils.isEmpty(orgIds)){
            return new HashMap();
        }
        BigDecimal orderQuantity = new BigDecimal(0);
        BigDecimal accumulativeOrderQuantity = new BigDecimal(0);
        for(String orgId:orgIds){
            if(orderInfoMap.get(orgId)!=null && orderInfoMap.get(orgId).get(date)!=null){
                MonthOrderQuantitySDO monthOrderQuantitySDO = orderInfoMap.get(orgId).get(date);
                //当日订单金额
                orderQuantity = orderQuantity.add(monthOrderQuantitySDO.getOrderAmount());
                //累计订单金额
                accumulativeOrderQuantity = accumulativeOrderQuantity.add(monthOrderQuantitySDO.getAccumulativeOrderAmount());
            }
        }
        Map<String,BigDecimal> result = new HashMap();
        result.put(ORDER_QUANTITY,orderQuantity);
        result.put(ACCUMULATIVE_ORDER_QUANTITY,accumulativeOrderQuantity);
        return result;
    }

    @FacadeInvoker
    private Map<String,Map<String,MonthOrderQuantitySDO>> querySalesOrgOrderQuantity(JobInitParam jobInitParam){
        Map<String,Map<String,MonthOrderQuantitySDO>> result = new HashMap<>();
        //查询60天内的所有销售组织每日订单量
        List<MonthOrderQuantitySDO> orderQuanList = statisticalOrderQuantityGroupByCreate(jobInitParam);
        Map<String,List<MonthOrderQuantitySDO>> orgOrderQuanMap = Nullable.stream(orderQuanList).collect(Collectors.groupingBy(MonthOrderQuantitySDO::getOrganizationId));
        //生成所有组织的每日订单量和累计订单量
        for (Map.Entry<String, List<MonthOrderQuantitySDO>> m : orgOrderQuanMap.entrySet()) {
            String record = jobInitParam.getToday();
            String orgId = m.getKey();
            List<MonthOrderQuantitySDO> orderList = m.getValue();
            Map<String, MonthOrderQuantitySDO> orderMap = orderList.stream().collect(Collectors.toMap(MonthOrderQuantitySDO::getGmtCreateDate,Function.identity(),(v1,v2)->v1));
            //生成60天内的每天订单量SDO
            List<MonthOrderQuantitySDO> newList = new ArrayList<>();
            for(int i =0;i<60;i++){
                MonthOrderQuantitySDO quantitySDO = new MonthOrderQuantitySDO();
                quantitySDO.setOrganizationId(orgId);
                quantitySDO.setGmtCreateDate(record);
                quantitySDO.setOrderAmount(orderMap.get(record)!=null?orderMap.get(record).getOrderAmount():new BigDecimal(0));
                Date statEndDate = DateUtils.parse(record);
                Date statBeginDate = DomUtil.getStartTimeOfMonth(statEndDate);
                List<MonthOrderQuantitySDO> accList = orderList.stream().filter(s -> statBeginDate.compareTo(DateUtils.parse(s.getGmtCreateDate()))<=0 && statEndDate.compareTo(DateUtils.parse(s.getGmtCreateDate()))>=0 ).collect(Collectors.toList());
                BigDecimal accOrderAmount = CollectionUtils.isNotEmpty(accList)?accList.stream().map(MonthOrderQuantitySDO::getOrderAmount).reduce(BigDecimal.ZERO,BigDecimal::add):new BigDecimal(0);
                quantitySDO.setAccumulativeOrderAmount(accOrderAmount);
                newList.add(quantitySDO);
                record = DomUtil.getRollbackDate(DateUtils.parse(record),-1);
            }
            Map<String,MonthOrderQuantitySDO> mmm = newList.stream().collect(Collectors.toMap(MonthOrderQuantitySDO::getGmtCreateDate, Function.identity(),(v1,v2)->v1));
            result.put(orgId,mmm);
        }
        log.info("<调拨单统计>monthOrderQuantityMap_result=={}",result);
        return result;
    }

    private List<MonthOrderQuantitySDO> statisticalOrderQuantityGroupByCreate(JobInitParam jobInitParam){
        //60天前那天的1号
        String queryBeginDate = DomUtil.getStartOfMonth(DateUtils.parse(jobInitParam.getTwoMonthAgo()))+" 00:00:00";
        String queryEndDate = jobInitParam.getToday()+" 23:59:59";
        CommPageQueryRequest queryTotalRequest = new CommPageQueryRequest();
        queryTotalRequest.setBeginDate(queryBeginDate);
        queryTotalRequest.setEndDate(queryEndDate);
        int total = allocateOrderDetailRepository.statisticalOrderQuantityGroupByCreateGetTotal(queryTotalRequest);
        int totalPage = (total + PageSize_500 - 1)/PageSize_500;
        List<Future<List<MonthOrderQuantitySDO>>> futureList = Lists.newArrayList();
        for (int pageNo = 0; pageNo < totalPage; pageNo++) {
            int start = pageNo*PageSize_500;
            CompletableFuture<List<MonthOrderQuantitySDO>> future = CompletableFuture.supplyAsync(() -> {
                CommPageQueryRequest queryRequest = new CommPageQueryRequest();
                queryRequest.setBeginDate(queryBeginDate);
                queryRequest.setEndDate(queryEndDate);
                queryRequest.setStart(start);
                queryRequest.setLimit(PageSize_500);
                Result<List<MonthOrderQuantitySDO>> result = null;
                try {
                    result = allocateOrderDetailRepository.statisticalOrderQuantityGroupByCreate(queryRequest);
                    if (result==null || CollectionUtils.isEmpty(result.getResult())){
                        return Lists.newArrayList();
                    }
                } catch (Exception e) {
                    log.error("statisticalOrderQuantityGroupByCreate_query_occor_error", e);
                    return Lists.newArrayList();
                }
                return result.getResult();
            }, monthSalesReportTaskExecutor);
            futureList.add(future);
        }
        List<MonthOrderQuantitySDO> result = new ArrayList<>();
        try {
            for (Future< List<MonthOrderQuantitySDO>> future : futureList){
                List<MonthOrderQuantitySDO> subList = future.get();
                result.addAll(subList);
            }
        }catch (Exception e){
            log.error("statisticalOrderQuantityGroupByCreate_future_get_occor_error", e);
        }
        log.info("<调拨单统计>statisticalOrderQuantityGroupByCreate_request={},total={},result_size={}", JSONObject.toJSON(queryTotalRequest),total,result.size());
        return result;
    }

    private Map<String, Map<String, BigDecimal>> queryCompanyOrderMonitorReport(String statisticalDate, List<String> orgIds){
        QueryOrderMonitorReportRequest queryRequest = new QueryOrderMonitorReportRequest();
        queryRequest.setOrganizationIds(orgIds);
        queryRequest.setStatisticalDate(statisticalDate);
        List<OrderProgressMonitorReportSDO> result = orderProgressMonitorReportQueryRepository.statisticalQueryCompanyOrderQuantity(queryRequest);
        Map<String, BigDecimal> orderQuantity = Nullable.stream(result).collect(Collectors.toMap(OrderProgressMonitorReportSDO::getOrganizationId, OrderProgressMonitorReportSDO::getOrderQuantity,(v1, v2)->v1));
        Map<String, BigDecimal> accumulativeOrderQuantity = Nullable.stream(result).collect(Collectors.toMap(OrderProgressMonitorReportSDO::getOrganizationId, OrderProgressMonitorReportSDO::getAccumulativeOrderQuantity,(v1, v2)->v1));
        Map<String, BigDecimal> monthFirstTaskMoney = Nullable.stream(result).collect(Collectors.toMap(OrderProgressMonitorReportSDO::getOrganizationId, OrderProgressMonitorReportSDO::getMonthFirstTaskMoney,(v1, v2)->v1));
        Map<String, BigDecimal> monthMiddleTaskMoney = Nullable.stream(result).collect(Collectors.toMap(OrderProgressMonitorReportSDO::getOrganizationId, OrderProgressMonitorReportSDO::getMonthMiddleTaskMoney,(v1, v2)->v1));
        Map<String, BigDecimal> monthLastTaskMoney = Nullable.stream(result).collect(Collectors.toMap(OrderProgressMonitorReportSDO::getOrganizationId, OrderProgressMonitorReportSDO::getMonthLastTaskMoney,(v1, v2)->v1));
        Map<String,Map<String, BigDecimal>> orderReport = new HashMap<>();
        orderReport.put(ORDER_QUANTITY,orderQuantity);
        orderReport.put(ACCUMULATIVE_ORDER_QUANTITY,accumulativeOrderQuantity);
        orderReport.put(MONTH_FIRST_TASK_MONEY,monthFirstTaskMoney);
        orderReport.put(MONTH_MIDDLE_TASK_MONEY,monthMiddleTaskMoney);
        orderReport.put(MONTH_LAST_TASK_MONEY,monthLastTaskMoney);
        return orderReport;
    }

    private Map<String, BigDecimal> queryContractQuantity(JobInitParam jobInitParam, List<String> orgIds, String orgType){
        if(CollectionUtils.isEmpty(orgIds)){
            return new HashMap<>();
        }
        BatchQueryContractQuantityRequest queryRequest = new BatchQueryContractQuantityRequest();
        queryRequest.setOrganizationIds(orgIds);
        queryRequest.setType(orgType);
        queryRequest.setContractYear(jobInitParam.getYear());
        queryRequest.setDataSource("103".equals(orgType)?ContractDataSourceEnum.CRM.getCode():ContractDataSourceEnum.CUSTOMER.getCode());
        List<Contract> result = planContractQuantityRepository.batchQueryContractByOrganiztion(queryRequest);
        Map<String, Contract> map = new HashMap<>();
        if("103".equals(orgType)){
            map = Nullable.stream(result).collect(Collectors.toMap(Contract::getOrgBusinessUnitCode, Function.identity(),(v1, v2)->v1));
        }else if("104".equals(orgType)){
            map = Nullable.stream(result).collect(Collectors.toMap(Contract::getOrgSalesOrganizationCode, Function.identity(),(v1, v2)->v1));
        }else if("105".equals(orgType)){
            map = Nullable.stream(result).collect(Collectors.toMap(Contract::getOrgSalesChannelCode, Function.identity(),(v1, v2)->v1));
        }
//        else if("106".equals(orgType)){
//            map = Nullable.stream(result).collect(Collectors.toMap(Contract::getOrgSalesDepartmentCode, Function.identity(),(v1, v2)->v1));
//        }
        Map<String, BigDecimal> convertMap = Nullable.stream(map.entrySet()).collect(Collectors.toMap(Map.Entry::getKey,entry -> getContractQuantity(entry.getValue(),jobInitParam.getMonth())));
        return convertMap;
    }

    public BigDecimal getContractQuantity(Contract contract, String month){
        BigDecimal amount = new BigDecimal(0);
        switch (month){
            case "1" :
                amount = new BigDecimal(contract.getJanTaxIncludedBeforeTax());
                break;
            case "2" :
                amount = new BigDecimal(contract.getFebTaxIncludedBeforeTax());
                break;
            case "3" :
                amount = new BigDecimal(contract.getMarTaxIncludedBeforeTax());
                break;
            case "4" :
                amount = new BigDecimal(contract.getAprTaxIncludedBeforeTax());
                break;
            case "5" :
                amount = new BigDecimal(contract.getMayTaxIncludedBeforeTax());
                break;
            case "6" :
                amount = new BigDecimal(contract.getJuneTaxIncludedBeforeTax());
                break;
            case "7" :
                amount = new BigDecimal(contract.getJulyTaxIncludedBeforeTax());
                break;
            case "8" :
                amount = new BigDecimal(contract.getAugTaxIncludedBeforeTax());
                break;
            case "9" :
                amount = new BigDecimal(contract.getSeptTaxIncludedBeforeTax());
                break;
            case "10" :
                amount = new BigDecimal(contract.getOctTaxIncludedBeforeTax());
                break;
            case "11" :
                amount = new BigDecimal(contract.getNovTaxIncludedBeforeTax());
                break;
            case "12" :
                amount = new BigDecimal(contract.getDecTaxIncludedBeforeTax());
                break;
        }
        return amount.divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
    }

    @Data
    private class JobInitParam{

        private Date todayDate;

        private String oneMonthAgo;

        private Date oneMonthAgoDate;

        private String twoMonthAgo;

        private Date twoMonthAgoDate;

        private String yesterday;

        private String today;

        private String thisMonthTimestamp;

        private String thisMonth;

        private Integer days;

        private String month;

        private String year;

        private String whenOfMonth;

        private Integer daysOfMonth;

        private OrganizationSDO nykTjCompanyOrg;

        private OrganizationSDO nykTjSalesOrg;

        private OrganizationSDO nykBjCompanyOrg;

        private OrganizationSDO nykBjSalesOrg;

        private OrganizationSDO commerceSalesOrg;

        private OrganizationSDO commerceCompanyOrg;

        private OrganizationSDO enterpriseGroupOrg;

        //查询所有销售组织31天内的每日订单金额和每日进度累计订单金额 （组织，日期，订单SDO）
        private Map<String,Map<String,MonthOrderQuantitySDO>> allocateOrderStatisticalMap;
        //查询原报表数据 (组织，SDO)
        private Map<String,OrderProgressMonitorReportSDO> reportMap;
        //查询月初报表数据 (组织，SDO)
        private Map<String,OrderProgressMonitorReportSDO> beginOfMonthReportMap;

        private Boolean isFirstSyncBusinessUnitReport;
        private Boolean isFirstSyncSalesOrgReport;
        private Boolean isFirstSyncChannelOrgReport;
    }

    //更新31天内的报表数据订单量
//            QueryOrderMonitorReportRequest queryRequest2 = new QueryOrderMonitorReportRequest();
//            queryRequest2.setBizType(orgType);
//            queryRequest2.setLimit(PageSize_500);
//            String statisticalDate = jobInitParam.getToday();
//            for(int j = 1; j<31; j++){
//                statisticalDate = DomUtil.getYesterdayByDate(DateUtils.parse(statisticalDate));
//                queryRequest2.setStatisticalDate(statisticalDate);
//                PageResult<List<OrderProgressMonitorReportSDO>> result = orderProgressMonitorReportQueryRepository.pageQueryOrderMonitorReportList(queryRequest2);
//                if(result.getTotal()==0){
//                    continue;
//                }
//                List<OrderProgressMonitorReportSDO> tmpList = result.getContent().stream().filter(x -> commerceSalesOrgCode.equals(x.getOrganizationCode())).collect(Collectors.toList());
//
//                for(OrderProgressMonitorReportSDO sdo:tmpList){
//                    //获取调拨单订单量
//                    Map<String,BigDecimal> orderAmount2 = new HashMap<>();
//                    if(jobInitParam.getEnterpriseGroupOrg() != null){
//                        String enterpriseGroupOrgId = jobInitParam.getEnterpriseGroupOrg().getId();
//                        orderAmount2 = getOrderQuantity(orderInfoMap,enterpriseGroupOrgId,statisticalDate);
//                    }
//                    //日订单金额
//                    BigDecimal orderQuantity = orderAmount2.get(ORDER_QUANTITY)!=null?orderAmount2.get(ORDER_QUANTITY):new BigDecimal(0);
//                    //累计订单金额
//                    BigDecimal accumulativeOrderQuantity = orderAmount2.get(ACCUMULATIVE_ORDER_QUANTITY)!=null?orderAmount2.get(ACCUMULATIVE_ORDER_QUANTITY):new BigDecimal(0);
//                    //判断新统计的订单量数据与旧数据的订单量和累计订单量值一样，跳过
//                    if(sdo.getOrderQuantity().compareTo(orderQuantity) == 0 && sdo.getAccumulativeOrderQuantity().compareTo(accumulativeOrderQuantity) == 0){
//                        continue;
//                    }
//                    //重新计算报表数据
//                    recountOrderComplete(sdo, orderQuantity, accumulativeOrderQuantity);
//                    int count = orderProgressMonitorReportWriteReporitory.update(sdo);
//                    log.info("<电商订单监控>{}更新历史统计数据，更新了{}条数据，{}", statisticalDate, count, JSON.toJSONString(sdo));
//                }
//            }

}
